javanetbeansperfect-numbers

Finding and printing perfect numbers under 10000 (Liang, Intro to Java, Exercise 5.33)


A perfect number is a number that's equal to the sum of all its positive divisors, excluding itself.

For my homework, I'm trying to write a program to find all four perfect numbers under 10000, but my code doesn't work when I run it and I'm not sure why (it just runs for a second or two, and then says "build successful" after not printing anything). I included it below, along with some comments that explain my thought process. Can someone help me out and tell me what's wrong with it?

public class HomeworkTwo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //Variable declaration

        int n;
        int possibleFactor;
        int factorSum=0;


        /**For each n, the program looks through all positive integers less than n  
           and tries to find factors of n. Once found, it adds them
           together and checks if the sum equals n. Then it repeats till n=9999. **/

        for (n=2; n<10000; n++) {
            for (possibleFactor = 1; possibleFactor < n; possibleFactor++) {
                if (n % possibleFactor == 0) {
                    factorSum = possibleFactor + factorSum;
                }

                //Is the number perfect? Printing
                if (factorSum == n) {
                    System.out.println(""+ n +" is a perfect number.");
                }
            }
        }
    }
}

Solution

  • You initialize factorSum to 0 before the first for loop, but you don't reset it to 0 when trying each new n. The factors keep adding up and are never equal tot he number to check. Reset it to 0 at the beginning of the n for loop.

    Also, you may want to move the test and print of the number being a perfect number after the inner for loop, but before the end of the outer for loop, or else it may print more than necessary.