Wednesday, February 2, 2011

Perfect Number Checking Program In BlueJ

What is perfect number



A number is considered as perfect number if the sum of its factors ( excepting the number itself) equals to the number. 6 is a perfect number as the factors of 6 are 1, 2, and 3 and sum of the factors is equal to 6.

How to check if a number is perfect or not



Take the number and find out the factors of the number using a loop. The sum of the factors are stored in a variable. At the end of the loop check the original number and the sum of the factors. If both the values are same, then the entered number is a perfect number otherwise not.


import java.io.*;
class PerfectNumber
{
int no,sum=0,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

 public void takeNumber()throws Exception
 {
System.out.println("Enter the number:");
no=Integer.parseInt(br.readLine());
 for(i=1;i< no;i++)
 {
  if(no%i==0)
  sum=sum+i;
 }
 if(sum==no)
 System.out.println(no + " is a perfect number");
 else
 System.out.println(no + " is not a perfect number");
}
public static void main(String args[])throws Exception
{
 PerfectNumber obj=new PerfectNumber ();
 obj.takeNumber();
}
}


Related PostBlueJ Programs on Number

2 comments:

  1. pleaseee tell me....Program in java to display palindrome numbers between 10 to 500 or any range,.

    ReplyDelete
    Replies
    1. class flag
      {
      int i,j;
      void show()
      {
      System.out.println("Palindrome numbers are\n");
      for(i=10;i<=500;i++)
      {
      if(palindrome(i))
      System.out.println(i);
      }
      }
      private boolean palindrome(int x)
      {
      int rev=0;
      for(j=x;j>0;j=j/10)
      {
      rev=rev*10+j%10;
      }
      if(rev==x)
      return true;
      else
      return false;
      }
      }

      Delete

Subscribe via email

Enter your email address:

Delivered by FeedBurner