Java code to check given number is perfect number or not
import java.io.*;
import java.io.*;
class Test {
public static void main(String[] args) throws IOException {
int n,i=1,sum=0;
System.out.println("Enter a number:-");
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
n=Integer.parseInt(br.readLine());
while(i>0){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
System.out.println("The no "+ i +" is a perfect number");
else
System.out.println("The no "+i+" is not a perfect number");
}
7 comments:
this is an infinite loop...:P
it has helped me doing my project work.
the above logic is wrong please change that code ;
keep i<n then it will be fine
no this is also gives wrong answer boss
infinite loop no output wrong program !!
This is the perfect program !!
import java.io.*;
class Perfect
{
public static void main(String[] args) throws IOException
{
int n,sum=0;
System.out.println("Enter a number:-");
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
n=Integer.parseInt(br.readLine());
for ( int i=1; i<n ; i++)
{
if(n%i==0)
sum=sum+i;
}
if(sum==n)
System.out.println("The no is a perfect number");
else
System.out.println("The no is not a perfect number");
}
}
import java.io.*;
class Perfect
{
public static void main(String[] args) throws IOException
{
int n,sum=0;
System.out.println("Enter a number:-");
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
n=Integer.parseInt(br.readLine());
for ( int i=1; i<n ; i++)
{
if(n%i==0)
sum=sum+i;
}
if(sum==n)
System.out.println("The no is a perfect number");
else
System.out.println("The no is not a perfect number");
}
}
Post a Comment