Perfect number program in java

Java code to check given number is perfect number or not


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:

Anonymous said...

this is an infinite loop...:P

Anonymous said...

it has helped me doing my project work.

Anonymous said...

the above logic is wrong please change that code ;
keep i<n then it will be fine

Anonymous said...

no this is also gives wrong answer boss

Jithin Sunny said...

infinite loop no output wrong program !!

Jithin Sunny said...

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");
}
}

Jithin Sunny said...

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");
}
}