Search code examples
javaperfect-numbers

Perfect numbers. Something wrong


I am trying to accomplish a task. To print 4 perfect numbers which are between 1 and 10000.

In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.

Here's my code:

public class PerfectNumbers
{
    public static void main(String[] args)
    {
        // Perfect numbers!

        for (int number = 1; number < 10000; number++)
        {
            int sum = 0;
            int i = 1;
            while (i < number)
            {

                if (number % i == 0)
                {
                    sum += i;
                    i++;

                }
                else
                {   
                    i++;
                    continue;
                }

                if (sum == number)
                {
                    System.out.println(number);
                }
                else
                {
                    continue;
                }

            }
        }
    }
}

The output is:

6
24 <--- This one is wrong because next must be 28. 
28
496
2016
8128
8190

What is wrong in my code? Thank you.


Solution

  • The if (sum == number) check needs to be done outside the loop. Otherwise you might pick up numbers such that the sum of a subset of divisors equals the number.

    In fact, 24 is one such example since 1+2+3+4+6+8=24. Your code prematurely concludes that 24 is perfect, despite it also being divisible by 12.