In this article we are going to discuss a problem from number system; this is one of the most commonly asked interview question of today.

Write a program in Java to check if a number is a perfect number or not.

e.g. A perfect number is a number that is half the sum of all of its positive divisors. The first perfect number is 6, because 1, 2 and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6.

We can find the easiest solution by iterating over to n/2 and check what are perfect divisors of the given number, than add them all to calculate if the sum is equals to the given number, related Java program is written below:

That?s it, we have seen how to Write a program in Java to check if a number is a perfect number or not. In upcoming articles we will see more about Java and Related programming problems and solutions.

package com.tbNext.byexample; public class TBPerfectNumber { public static void main(String[] args) { TBPerfectNumber perfectNumber = new TBPerfectNumber(); System.out.println("Is 28 a perfect number: " + perfectNumber.isPerfectNumber(6)); System.out.println("Is 10 a perfect number: " + perfectNumber.isPerfectNumber(10)); System.out.println("Is 6 a perfect number: " + perfectNumber.isPerfectNumber(6)); } private boolean isPerfectNumber(int n) { int sum = 0; for (int i = 1; i <= n / 2; i++) { if (n % i == 0) sum += i; } if (sum == n) return true; return false; } }

**Output:**
Is 28 a perfect number: true

Is 10 a perfect number: false

Is 6 a perfect number: true

Is 10 a perfect number: false

Is 6 a perfect number: true

That?s it, we have seen how to Write a program in Java to check if a number is a perfect number or not. In upcoming articles we will see more about Java and Related programming problems and solutions.

### About The Author

#### Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.