Semi Perfect/Pseudo Perfect Number in JAVA
Question : Write a program to accept a number and check whether it is Semi-Perfect number or not.
Semi-Perfect Number : A Semi-Perfect number or Pseudo-Perfect number is a natural number n that is equal to the sum of all or some of its proper divisors.
A Semi-Perfect number that is equal to the sum of all its proper divisors is a perfect number.
First few Semi-Perfect numbers are: 6, 12, 18, 20, 24, 28, 30, 36, 40 etc.
Proper Divisors : Proper divisor is a positive divisor of a number, excluding itself.
Example :-
Input : 6
Proper Divisors of 6 : 1, 2, 3
Sum of Proper Divisors : 1 + 2 + 3 = 6
Output : Semi-Perfect Number (Since sum of all the factors is equal to the number, it is also a Perfect Number).
Input : 12
Proper Divisors of 12 : 1, 2, 3, 4, 6
Sum of Proper Divisors : 1 + 2 + 3 + 6 = 12
Output : Semi-Perfect Number
Program to check whether the number is Semi-Perfect or not :-
Program :-
import java.io.*;
import java.util.*;
class Semi_Perfect
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n,c=0,s=0,a=0,i,j,k,x,temp,d=0;
System.out.println("Enter Number");
n= in.nextInt(); //input number
for(i=1;i<n;i++)
{
if(n%i==0)
{
c++;//calculating no. of factors
}
}
x=(int) Math.pow(2,c); //storing no.of subsets required
int ar[]=new int[x]; //declaring int type array
for(i=1;i<n;i++)
{
if(n%i==0)
{
ar[a]=i;//storing factors in Array
a++;
}
}
for(i=0;i<c;i++)
{
for(j=0;j<c;j++)
{
for(k=j;k<c;k++)
{
s=s+ar[k];
if(s==n)//if the number is semi-perfect
{
d=1;
break;
}
}
if(d==1)
{
break;
}
temp=ar[j]; //swapping array elements
ar[j]=ar[j+1];
ar[j+1]=temp;
s=0;
}
if(d==1)
{
break;
}
}
if(d==1)
{
System.out.println("It is a Semi-Perfect Number : "+n);
}
else
{
System.out.println("It is not a Semi-Perfect Number : "+n);
}
}//end of main method
}//end of class
For Proper Understanding Watch the Video :-
All the best :)
Keep Learning :)
Comments
Post a Comment