Java Program to Check Perfect Number

You are Here:

What is Perfect Number?

A positive integer that is equal to the sum of its proper divisors.

For example, 6 is a perfect number
6 = 1 + 2 + 3
6 = 6

Tips: It is recommended to use our online Perfect Number calculator for better understanding.

Check Perfect Number

In the following example, we will check whether the given number (496) is a Perfect number or not.

Example

Java Compiler
public class myClass { public static void main(String[] args) { int num = 496; int i = 1; int total = 0; for(i=1; i<num; i++) { if(num % i == 0) total += i; } if(total == num) System.out.format("%d is a perfect number", num); else System.out.format("%d is not a perfect number", num); } }

Output

496 is a perfect number

Perfect Numbers between the Given Range

In the following example, we will find all the Perfect numbers between 1 and 1000.

Example

Java Compiler
public class myClass { public static void main(String[] args) { int start = 1; int end = 1000; int i = 1; int total = 0; int flag = 0; System.out.format("Perfect numbers between %d and %d:\n", start, end); for(start=start; start<=end; start++) { for(i=1; i<start; i++) { if(start % i == 0) total += i; } if((total == start) && (start != 0)) { flag = 1; System.out.print(start +" "); } total = 0; } if(flag == 0) System.out.print("There in no perfect number between the given range"); } }

Output

Perfect numbers between 1 and 1000: 6 28 496

Check Whether the Given Number is Perfect or Not

In the following example, we will check whether the given number is a Perfect Number or Not.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a (int) number: "); int num = reader.nextInt(); int i = 1; int total = 0; for(i=1; i<num; i++) { if(num % i == 0) total += i; } if(total == num) System.out.format("%d is a perfect number", num); else System.out.format("%d is not a perfect number", num); } }

Output

Enter a (int) number: 25 25 is not a perfect number

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author