Java Program to print perfect numbers between two given numbers

A number is called perfect number, if the number is equal to the sum of all of its factors except itself. For example, 6 , 28 are perfect numbers.

Factors of 6 (Except 6) are 1 , 2 , 3. Sum of 1+2+3=6

Factors of 28 (Except 28) are 1, 2, 4, 7, 14. Sum of 1+2+4+7+14 = 28

Now the following program prints all the perfect numbers between two given numbers .

package com.javaonline;

import java.util.Scanner;
class PerfectNumberWithJava
{
public static void main(String main[])
{
	Scanner sc = new Scanner(System.in);
	System.out.println("Enter Start Number");
	int start=sc.nextInt();
	System.out.println("Enter End Number");
	int end=sc.nextInt();
	System.out.println("Perfect Numbers between " + start + " and " + end + " are :");
	for (int i=start; i<=end; i++)
	{
	int sum=0;
	for (int j=1 ; j<i;j++)
		{
			if (i % j==0)  sum=sum+j;
		}
	 if (i==sum) System.out.print(i + "\t");
	}
}
}

Output :

Perfect Number java

You may also like

Leave a Reply