Here is a java program to check whether a number is perfect number or not. A perfect number is a number whose sum of all the divisors is equal to the number itself.

Examples of Perfect Numbers :

6 = 1 + 2 + 3, (1, 2 and 3 are proper divisors of 6).

28 = 1 + 2 + 4 + 7 + 14 (1, 2, 4, 7, 14 are proper divisors of 28).

In this java program, we have to check whether a given number is an perfect number or not and print the result on screen.

**Algorithm to check a number is perfect number or not**

Let N be the given number.

- Find all divisors of a N between 1 to N/2.
- Add the values of all divisors to a variable sum.
- If sum is equal to N, then N is a perfect number otherwise not a perfect number.

## Java program to check perfect number or not

This program first takes a number as input from user and stores it in variable 'N'. Using a for loop, we iterate from 1 to N/2 to find the sum of all divisors of N. If divisor sum is equal to N, then N is a perfect number else not a perfect number.

package com.tcc.java.programs; import java.util.Scanner; public class PerfectNumber { public static void main(String[] args) { int N, i, divSum; Scanner scanner; scanner = new Scanner(System.in); System.out.println("Enter an Integer"); N = scanner.nextInt(); /* * Find the sum of all divisors of a N between 1 to N/2 */ for (divSum = 0, i = 1; i <= N / 2; i++) { if (N % i == 0) { divSum += i; } } if (divSum == N) System.out.format("%d is Perfect Number", N); else System.out.format("%d is Not a Perfect Number", N); } }Output

Enter an Integer 6 6 is Perfect Number

Enter an Integer 12 12 is Not a Perfect Number

**Recommended Posts**