Design a class Perfect to check if a given number is a perfect number or not. (A number is said to be perfect if sum of the factors of the number excluding itself is equal to the original number.)
Example : 6= 1+2+3 ( where 1, 2 and 3 are the factors of 6, excluding itself)
Class name : Perfect
Data members:
num : to store the number
Member methods:
Perfect(int nn) : initialize the data member num=nn
int sumofFact(int i) : return the sum of the factors of the number, excluding itself, using recursive technique.
void check() : checks whether the given number is perfect by invoking the function sumofFact() and displays the result with an appropriate message.
Specify the class and define main() to create an object and call the functions accordingly to enable the task.
Program:
import java.util.*;
class Perfect
{
int num;
Perfect(int nn)
{
num=nn;
}
public int sumofFact(int i)
{
int n=num;
if(i>n/2)
return 1;
else
{
if(n %i==0)
return i +sumofFact(i+1);
else
return sumofFact(i+1);
}
}
public void check()
{
int s=sumofFact(2);
if(s==num)
System.out.println(num+”is a perfect number”);
else
System.out.println(num+”is not a perfect number”);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a number”);
int n= sc.nextInt();
Perfect obj=new Perfect(n);
obj.check();
}
}
Output:
Enter a number
28
28 is a perfect number
Enter a number
8128
8128 is a perfect number
Enter a number
46
46 is not a perfect number