Search code examples
javaloopsfor-loopperfect-numbers

"for" loop and perfect numbers


Have to create program that list all perfect number( sum of factors = number ) 1 - 1000.

  • this is for a java class, need to only use "for" loops

I have checked my code 100 times and getting no output, I am missing a logical error somewhere, could someone help me out?

public static void main(String[] args)
{
  // variables
  int total = 0;
  final int LIMIT = 1000;

  // for loop to test all numbers 1-1000
  for(int i = 1; i <= LIMIT; i++)
  {
    // if statement
    if((i != 1) && (total == i - 1))
    {
      // prints perfect number
      System.out.println((i - 1) + " is a perfect number");
      // resets total value
      total = 0;
    }
    // gets and add factors as total
    for(int divider = 1; divider < i; divider++)
    {
      if((i % divider) == 0)
      {
        total += divider;
      }
    }
  }
}

Solution

  • Your big problem is that you only reset total if you find a perfect number. If you don't find a perfect number, you continue adding divisors for the next number to the old total. You need to start fresh for every i.

    Rearranging your program in the following way should help:

    public static void main(String[] args) {
        final int LIMIT = 1000;
        for (int i = 0; i <= LIMIT; i++) {
            // Declare total here, inside the loop, so values from previous
            // iterations are discarded.
            int total = 0;
            for (/* your code here */) {
                // add up divisors
                // your code here
            }
            // compare to i, rather than always computing the total for the
            // previous number and comparing to that.
            if (/* your code here */) {
                // print output
                // your code here
            }
        }
    }