Write a Program to check perfect numbers or Not


The program starts with a Check_Perfect() method that takes a number as an argument and checks whether it is a Perfect Number or not. It first checks if the number is 1. If it is, the method immediately returns false, as 1 is not considered a Perfect Number. Otherwise, it initializes sum as 1 and then iterates over all the possible divisors of the number up to n-1. For each divisor, it checks if it divides n without leaving a remainder. If it does, it adds it to the sum.

After the loop completes, the method checks whether the sum is equal to the n. If it is, the method returns true, indicating that the number is a Perfect Number. If it is not, the method returns false.

The program then takes an input number from the user using the Scanner class and calls the Check_Perfect() method to check whether the number is a Perfect Number or not. If it is, the program prints that the number is a Perfect Number. Otherwise, it prints that the number is not a Perfect Number.

Source Code

import java.util.Scanner;  
class Perfect_Number
{ 
	static boolean Check_Perfect(int n) 
	{  
		if (n == 1) 
			return false;
		int sum = 1;
		for (int i = 2; i < n; i++) { 
 
			if (n % i == 0) { 
				sum += i; 
			} 			
		}
		if (sum == n) 
			return true; 
 
		return false; 
	} 
 
	public static void main(String[] args) 
	{ 
        Scanner input = new Scanner(System.in);		
        System.out.print("Enter The Number : ");
        int n = input.nextInt();
		if (Check_Perfect(n)) 
			System.out.println(n + " is a Perfect Number"); 
		else
			System.out.println(n + " is not a Perfect Number"); 
	} 
}
 

Output

Enter The Number : 6
6 is a Perfect Number

Example Programs