Written by Sai Sameera Thota on February 16, 2013 in Java > Programming

Java Program to Find if a Number is Perfect or not

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This program is used to check whether a given number is a perfect number or not. So what is a Perfect Number? A perfect number is any integer that equals the sum of its divisors(including 1 and excluding the number itself). For example, consider the number 6. The divisors of 6 are 1,2,3,6. Excluding the number itself i.e, 6, the sum of other divisors is equal to 6 (1+2+3 = 6). Hence 6 is a perfect number.

Java Program to find if a Number is Perfect or not

import java.io.*;
import java.util.*;
class perfect
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("\nEnter a number:");
		int n = Integer.parseInt(br.readLine());
		int sum = 0;
		for(int i=1;i<n;i++)
		{
			if(n%i==0)
			{
				sum = sum + i;
			}
		}
		if(sum == n)
			System.out.println("\nGiven number is a perfect number");
		else
			System.out.println("\nGiven number is not perfect number");
	}
}

Output:
perfect

Java Program to find list of Perfect Numbers in a Given range

//Java program to display perfect numbers in a given range
import java.io.*;
class perfect_list 
{
	public static void main(String[] args) throws IOException 
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("\nEnter the range:");
		long range = Long.parseLong(br.readLine());
		System.out.println("\nThe perfect numbers between 1 and "+range+" are:");
		for(int i=1;i<range;i++)
		{
			int sum = 0;
			{
				for(int j=1;j<i;j++)
				{
					if(i%j == 0)
					{
						sum = sum + j;
					}
				}
				if(sum == i)
				{
					System.out.println(i);
				}
			}
		}
	}
}

Output:
perfect_list

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: