Search code examples
javaperfect-numbers

Not printing perfect numbers


Here is my code :-

package javaapplication;

import java.util.Scanner;

public class perfect02 {

    public static void main(String args[]) {
        int i = 1, sum = 0;

        System.out.println("Enter maximum range : ");
        Scanner kb = new Scanner(System.in);

        int a = kb.nextInt();
        System.out.println("Enter minimum range : ");

        Scanner kb2 = new Scanner(System.in);
        int b = kb2.nextInt();

        System.out.println("perfect number in the given range are :");
        for (int n = b; n <= a; n++) {
            while (i < n) {
                if (n % i == 0) {
                    sum = sum + i;
                }
                i++;
            }
            if (sum == n)
                System.out.println(+n + " ");
        }
    }
}

Why program is not printing perfect numbers ?

I have checked code many times but i am unable to find the solution .Please tell me what is going wrong in my code .Thanks in advance

Any help would be appreciated ....


Solution

  • Here, I looked into the perfect number generation and fixed it for you!

    public static void main(String args[]) {
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter minimum range : ");
        int b = kb.nextInt();
        System.out.println("Enter maximum range : ");
        int a = kb.nextInt();
        kb.close();
        System.out.println("Perfect number in the given range are :");
        for (int n = b; n <= a; n++) {
            int sum = 0;
            int i = 1;
            while (i < n) {
                if (n % i == 0)
                    sum = sum + i;
                i++;
            }
            if (sum == n)
                System.out.println(n + " is perfect");
    
        }
    }
    

    You should've had the sum and i variables declared inside the for loop, so they would be reset for each number!