How can I use a “for” loop to find the first 3 perfect numbers after 28?
Here is some code I’m using.
I can’t seem to get anything past 2 numbers. If I try to increase i<= 2000000000 it tells me the integer is to large.
public class JBaneling
{
public static void main(String args[])
{
System.out.println("3 nearest Perfect numbers after 29 ");
for (int i = 29; i <= 2000000000; i++) {
test1(i);
}
}
public static void test1(int number)
{
int sum = 0;
for(int divisor=1; divisor < number; divisor++)
{
if ((number % divisor) ==0)
{
sum = sum + divisor;
}
}
if(sum==number)
{
System.out.println(number + " is a perfect number");
}
}
}
It’s just taking a long time to compute the third perfect number. After
8128the next perfect number is33550336. Now consider that your code is testing every integer between8128 ... 33550336, by computing each divisor of each of those integers.Also consider that this next perfect number,
33550336is the largest perfect number that you’ll be able to represent with a javaint:Integer.MAX_VALUEis (2^31 – 1). You’ll get a few more with along–Long.MAX_VALUEis (2^63 – 1) – but you’ll be waiting a long time for that 8th perfect number.Note that you only need to consider divisors up to the square root of
number, then find their matching divisor above the square root, but even so you’ll still need to wait a really long time before getting to the next perfect number.