-2

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);
            }
        }
    }
}
akash
  • 22,664
  • 11
  • 59
  • 87
Sadra Reihan
  • 3
  • 1
  • 2

1 Answers1

0

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249