Perfect Numbers In Java - ICSE Examples
14-05-2018    331 times
Perfect Numbers

Perfect No In Java - ICSE Examples

Write a program to print all the perfect nos between two limit enterd by the user with help of the following function
 

boolean IsPerfect(int num) - to return true if num is perfect otherwise print false.

A Number is said to be perfect if sum of all factors excluding itself should be equal to the number. Let N=6, Its factors are 1,2,3 and the sum of the factors (1+2+3)=6. So 6 is the perfect no. Examples of some Other perfect numbers are 28 and 496.


void showPerfectNumbers(int start,int end) - to print all the perfect nos between start and end limits by using functions IsPerfect().

Write a main function to execute the same.

Tutorial at home
import java.util.*;
public class PerfectNumbers
{
    public boolean IsPerfect(int num)
    {
        int sum=0;
        for(int k=1;k<= num/2;k++)
        {
            if(num%k==0)
            {
                sum=sum+k;
            }
        }
        if(sum==num)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public void showPerfectNumbers(int start, int end)
    {
        System.out.println("Perfect Numbers are \n================");
        for(int i=start;i<=end;i++)
        {
             if(IsPerfect(i))
             {
                   System.out.println(i);
             }
        }
    }
    public static void main(String []args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter Start Number:");
        int s=sc.nextInt();
        System.out.print("Enter end Number:");
        int e=sc.nextInt();
        PerfectNumbers pn=new PerfectNumbers();
        pn.showPerfectNumbers(s,e);
    }
}
Tutorial at home

Output


Enter Start Number:2
Enter end Number:900

Perfect Numbers are
================
6
28
496

softetechnologies
    Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
    Related Post
  Query About the post