Home Tutorial Java Core Check Perfect Number in Java Program

 
 

Share on Google+Share on Google+
Check Perfect Number in Java Program
Posted on: November 9, 2009 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Check Perfect Number in Java Program:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 9, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com