promotion image of download ymail app

Need java help with practice question?

Attachment image

1 Answer

  • 9 months ago

    That's a weird opening sentence in your problem statement. A perfect number is a single number, not a "series of ... numbers". Change that to, "The perfect numbers are a sequence of special natural numbers." and the rest works.

    If you want to solve a problem like this, one way is to type it into a main class and run it to see what output you get. I do mean "type", by the way, and not "copy/paste".

    As you are typing, ask yourself, "What is this statement trying to do?" Then ask, "Is this really a valid way to do that?"

    I'll give one spoiler here. When you get to the "if (n / k == 0)" line, my answer to the first question is, "The coder is trying to test if k is a divisor of n." The second question gets a, "No." If k is a divisor of n, then the remainder (n%k) will be zero, not the quotient (n/k).

    If you can't find the other errors this way, add debug code to print out the divisors found in the loop (you'll need to add {} braces to the if statement in the inner loop) and the sum of divisors at the end. Check these by hand.

    A web search for "perfect number" is a good idea, to find a list of known perfect numbers and their divisors. It's a short list. Only the first five of them will fit in a Java int or Integer, and this program won't find the fifth one unless you're willing to let it run for months or perhaps years.

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.