Trying to find a a perfect number within an upper limit in java without creating a method

Viewed 66

I'm just trying to print the perfect numbers within a certain upper limit, but I get other numbers that show up, that aren't perfect numbers. I'm not trying to use a method, rather than just everything in the main loop. I need some help.

public static void main(String arg[]) {
    int upper;
    int sum = 0;   
    int i;
    System.out.println("Enter upper limit");
    Scanner stnd = new Scanner(System.in);
    upper = stnd.nextInt();
    
    for(int n = 1; n < upper;  n++) {
      i = 1;
      sum = 0;

      while (i <= n/2) {
        if (n%i == 0) {
          sum = sum + i;  
        }
        i++;
    
        if(sum == n) {      
          System.out.println(n+" is a perfect number");
          break;
        } else {
        }
      }
    }
}
1 Answers

You've got a while loop in your code that adds up the factors of the number. The problem is that you're checking the sum, when the while loop isn't yet finished. In the case of 24, you've added up

1 + 2 + 3 + 4 + 6 + 8

which is 24, but your loop hasn't got to 12 yet.

You need to move

if(sum == n) {      
     System.out.println(n+" is a perfect number");
}

to after the while loop, rather than having it inside the loop.

Related