Java program to check if a number is perfect or not

Java program to check if a number is perfect or not :

In this tutorial, we will learn how to check if a number is perfect or not. User will enter one number and we will check if it is perfect or not and print out the result.

What is a Perfect number :

A number whose sum of all divisors is equal to the number is called a perfect number . For example, the divisors of 6 is 1,2 and 3. The sum of these divisors is (1 + 2 + 3) = 6. So, it is a perfect number. But 5 or 7 is not. Let’s take a look into the program :

Java Program :

import java.util.Scanner;

public class Main {

    //7
    /**
     * Utility function for System.out.println
     *
     * @param message : string to print
     */
    private static void println(String message) {
        System.out.println(message);
    }


    /**
     * Utility function for System.out.print
     *
     * @param message : string to print
     */
    private static void print(String message) {
        System.out.print(message);
    }

    /**
     * main method
     *
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws java.lang.Exception {
        //1
        Scanner scanner = new Scanner(System.in);

        //2
        int no;
        int sum = 0;

        //3
        print("Enter the number : ");
        no = scanner.nextInt();

        //4
        for (int i = 1; i <= no / 2; i++) {
            //5
            if (no % i == 0) {
                sum += i;
            }
        }

        //6
        if (sum == no) {
            println(no + " is a Perfect number");
        } else {
            println(no + " is not a Perfect number");
        }

    }

}

Sample Output :

Enter the number : 29
29 is not a Perfect number

Enter the number : 28
28 is a Perfect number

Enter the number : 5
5 is not a Perfect number

Algorithm :

In the above example, we have marked some lines with numbers . Following step-numbers is same as the number above :

1. Create one ‘Scanner‘ object to read the input number.
2. Create one variable to store the number and one variable to store the sum.
3. Read the number user entered using ‘Scanner‘.
4. Run one loop and from 1 to ‘number/2’.
5. Check for each number if it is a perfect divisor of the user input number, add this number to the ‘sum’.
6. After the loop is completed, check if the ‘sum‘ is equal to the number or not. If equal, print it as a ‘Perfect‘ number. Else it is not.

Sitewide-USD 336x280

Leave a Reply