Search code examples
javaif-statementfor-loopperfect-numbers

Printing all perfect and non perfect numbers 6 to n


I'm trying to print all from 6 to n but when i run the code it gives me all the numbers but not the right perfect numbers. For example when I enter 30 it prints out all numbers but it says only 6 and 7 are perfect numbers only 7 is not a perfect number and 28 is.

import java.util.Scanner;


public class PerfectN {

public static void main(String[] args) {


            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter a number that is 6 or above: ");
            int n = scanner.nextInt();

            int sum = 0;

            if(n<6){
                System.out.println("Incorrect number.");
            }
            else
                for(int i = 6;i<=n;i++){
                    for(int j = 1; j<i; j++){
                        if(i%j==0)
                            sum += j;
                    }


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



            else
                    System.out.println(i + " is not a perfect number.");

            }
        }

}

Solution

  • You need to reset the sum variable to zero for each number you go through:

    for (int i = 6; i <= n; i++) {
        int sum = 0;
        for (int j = 1; j < i; j++) {