I try to find the perfect number between 1 and 1000, i wrote this code but it didn't work! what is wrong?
public class Perfect {
public static void main(String[]args) {
int sum=0;
for (int n = 1; n < 1000; n++) {
for (int j = 1; j < n/2 ; j++) {
if (n % j == 0)
sum = sum + j;
}
if (sum == n) {
System.out.println(sum);
}
}
}
}
Move the declaration (and more importantly the initialization) of sum
into the for
loop. Also, you need to test <=
in the inner loop. Something like,
for (int n = 1; n < 1000; n++) {
int sum = 0;
for (int j = 1; j <= n / 2; j++) {
And I get 496
.