Follow @devglan

# Java Program To Check If A Given Number is A Perfect Number

## Description

Perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. Following are the examples of perfect number.

6= 1+2+3 28= 1+2+4+7+14 496= 1+2+4+8+16+31+62+124+248

Following is the java program to check if a given number is a perfct number or not.

**PerfectNumber.java**

package com.devglan.set1; public class PerfectNumber { public void checkPerfectNumber(int num){ int divisorSum = 1; for(int i = 2; i <= num/2; i++) if(num % i == 0) divisorSum += i; if(divisorSum == num) { System.out.print("Given number " + num + " is a perfect number."); }else { System.out.print("Given number " + num + " is not a perfect number."); } } public static void main(String [] args){ PerfectNumber perfectNumber = new PerfectNumber(); perfectNumber.checkPerfectNumber(28); } }

## Explanation

#### Click to Suggest Your Own Explanation

A perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. ?1(n) = 2n. Hence, run a for loop and keep adding the those number which is an exact divisor of given number and finally if the sum is equal to the given number itself then the given number is a perfect number.