In this program user will enter a number and the program will show
whether it is a perfect number. If the entered number is not a perfect number
then the nearest higher value of the entered number which is a perfect number
will be displayed.
BlueJ Codes of the Perfect Number Checking Program
class border
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int i,s,n,j;
public void take()throws
IOException
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
j=n;
s=0;
for(i=1;i< n;i++)
{
if(n%i==0)
s=s+i;
}
if(s==n)
System.out.println("Number = "+ n + " is a perfect
number");
else
{
s=0;
n++;
while(true)
{
for(i=1;i< n;i++)
{
if(n%i==0)
s=s+i;
}
if(s==n)
{
System.out.println(n+ " is perfect number nearest to "+j);
break;
}
else
{
s=0;
n++;
}
}
}
}
public static void main(String args[])throws IOException
{
border ob=new border();
ob.take();
}
}
Technical Analysis of the perfect number program using BlueJ
If the entered number is a perfect number then the matter is
solved otherwise an infinite while loop is executed and the entered number is
incremented by one every time the new number is found not perfect number. When
the incremented number is found to be perfect number, the result is displayed
and the infinite loop is terminated.
Sample Input and Output of the perfect number program
Enter the number:
7
28 is perfect number nearest to 7
Enter the number:
28
Number = 28 is a perfect number
Enter the number:
5
6 is perfect number nearest to 5
Related posts:
No comments:
Post a Comment