Reputation: 33
i was trying some code regarding perfect numbers, i wrote a code that should show me the first n perfect numbers i ask for, but it shows only the first 4 numbers, always...
i already tried to switch places with various counters and so on, but none of that works
public static void main(String[]args){
int n; //counter
long N = 6; //starting point of the perfect numbers
System.out.print("Please enter n: "); //maximum value of the counter
n = in.nextInt();
while (n > 0) { //first loop and control of the counter
int sum = 0, i = 1; //initialization of the variables i need for the following loop
while (i < N -1) { //control for the iterations, maximum value is N - 1(all the numbers except N)
if (N % i == 0) { //control if i is a divider
sum = sum + i; // if i ist a divider than i add it to the variable sum
}
i++; // i increment
}
if (sum == N) { //final control, if sum is equal to N, than i print it
System.out.print(N + " ");
n--; //decrement of the counter, so that it shows me only the numbers i ask
}
N++; //increment of the number to control
}
}
it should show me the first n numbers i ask, example n = 5 result 6, 28, 496, 8128, 33550336
Actual result is always the first four.
Upvotes: 2
Views: 95
Reputation: 59302
Just wait long enough.
It takes 30 ms to calculate the third number and 10 seconds for the fourth.
To reach the number 20.000, it takes already 53 seconds. So for 33.000.000, it may take 87.450 seconds = 24.3 hours. Or even longer, since it doesn't look linear:
6 after 0.0
28 after 0.0
496 after 0.033
8128 after 10.38
10000 ... 5.54
20000 ... 53.01 (estimate 24 h)
30000 ... 132.63
40000 ... 244.09
50000 ... 387.71
60000 ... 563.20 (estimate 86 h)
70000 ... 771.75
80000 ... 1010.81 (estimate 115 h)
If you told us that the program never exits, that would have been helpful.
Upvotes: 3