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:

  1. this is an infinite loop...:P

    ReplyDelete
  2. it has helped me doing my project work.

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

    ReplyDelete
    Replies
    1. no this is also gives wrong answer boss

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

      Delete
  4. infinite loop no output wrong program !!

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

    ReplyDelete