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.
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.Your code prints 24 because when you step through the loop as i = 8 the sum of all numbers is 1+2+3+4+6+8 = 24 so your condition gets met. You need to add another conditional to the print to prevent it from printing when the summation has not yet been completed. In this case you haven't yet added 12 to make the calculation valid.
I would move the if statement outside the while loop so it is checked only after your sum is calculated.