Home Tutorial Java Core Check Perfect Number in Java Program

 
 

Check Perfect Number in Java Program
Posted on: November 9, 2009 at 12:00 AM
In this Java Tutorial section, we are going to check whether number is perfect or not.

How to Check Perfect Number in Java Program

A perfect number is a positive integer where the sum of all its positive divisors, except itself, is equal to the number itself. For example 6 is a perfect number as 1,2 and3 are its divisors and the sum of divisors=1+2+3=6. Here we have created a program that will take the number from the user and reports whether it is perfect or not.

Here is the code:

import java.util.*;

public class PerfectNumber {
	public static void main(String[] args) {
		System.out.println("Enter any number");
		Scanner input = new Scanner(System.in);
		int num = input.nextInt();
		int perfectNo = 0;
		int i;
		System.out.println("Factors are:");
		for (i = 1; i < num; i++) {
			if (num % i == 0) {
				perfectNo += i;
				System.out.println(i);
			}
		}
		if (perfectNo == num) {
			System.out.println("number is a perfect number");
		} else {
			System.out.println("number is not a perfect number");
		}
	}
}

Output:

Enter any number
28
Factors are:
1
2
7
14
number is a perfect number

Related Tags for Check Perfect Number in Java Program:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.