Java Programs

Perfect number program

We will learn how to write a program in Java to check whether a certain number is perfect or not.

How will this Java program behave?

The Java program for perfect numbers is written below. This program will take a positive number as input and after performing some operations will output whether the given number is perfect or not.

Suppose you want to check a number whether it is perfect or not, then you need to take this number as input to the program below when it is executed.

After the calculation it will give you the corresponding output.

Program:

import java.util.Scanner;

public class Main {

	public static void main(String ...args) {
        int remainder, sum = 0, i, originalNum;
        Scanner sc = new Scanner(System.in);
        System.out.print("please enter a number: ");  
        originalNum = sc.nextInt();  
        
        for (i = 1; i <= originalNum/2; i++)
        {
            remainder = originalNum % i;
	        if (remainder == 0)
            {
                sum = sum + i;
            }
        }
        
        if (sum == originalNum)
            System.out.print("Given no. is perfect number");
        else
            System.out.print("Given no. is not a perfect number");
    }	
}

Output:

please enter a number: 6
Given no. is perfect number

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs