Perfect Number Program in Java

In this post we will develop a Java program to check the number is a perfect number or not. We will try to develop a method which will give high performance, and we will also develop a Java program to find all perfect number which belongs to a given range.

Perfect number:- A number whose factors sum except itself, is equal to the same number is called a perfect number.

Example:- 6
Factors of 6 (except itself) are 1,2,3.
The Sum of these factors 1+2+3 = 6 So, 6 is a Perfect number.

Another example:- 28
Factors of 28 (except itself) are 1, 2, 4, 7, 14
The sum of factors of 28 = 1+2+4+7+14 = 28
Hence, 28 is also a perfect number.

Logic to check perfect number in Java

1) Take a number
2) Take a variable sum_of_factors and initialize it with 0
3) find the factors of the number (except itself)
4) Add the factors in the variable sum_of_factors
5) If sum_of_factors is equal to the input (number) then it is a perfect number

Java Code for the Perfect Number

We need to find the factor except for itself so it is a better idea to iterate the loop only for number/2 times, because if we exclude the number then all factors of the number will be less than or equal to the half of the number. For example:- Except itself, the factors of 10 are 1, 2 and 5. Those all are less than or equal to the half of the number 10 i.e. 10/2=5

// Check the number is perfect number or not
public static boolean isPerfect(int number) {

   // declare variables
   int sum_of_factors = 0;

   // find factors of the number
   for(int i=1; i<= number/2; i++)
       if(number%i == 0)
           // add factor in sum_of_factors
           sum_of_factors += i; 

   // compare sum_of_factors and number
   if (sum_of_factors == number)
       return true; // perfect number
   return false; // not a perfect number
}

Also see:- Special numberMagic numberArmstrong numberPerfect numberEvil NumberSpy NumberSunny number in Java

Java program to check perfect number

Based on the above method we can write a Java program to check the given number is a perfect number or not.

import java.util.Scanner;

public class PerfectNumber {

   // Check the number is perfect number or not
   public static boolean isPerfect(int number) {

      // declare variables
      int sum_of_factors = 0;

      // find factors of the number
      for(int i=1; i<= number/2; i++)
          if(number%i == 0)
             // add factor in sum_of_factors
             sum_of_factors += i; 

      // compare sum_of_factors and number
      if (sum_of_factors == number)
          return true; // perfect number

      return false; // not a perfect number
   }

   public static void main(String[] args) {

      // declare variables
      int number = 0;
      boolean result = false;

      //create Scanner class object to take input
      Scanner scan = new Scanner(System.in);

      // take input from end-user
      System.out.print("Enter an integer number:: ");
      number = scan.nextInt();

      // check number is perfect number or not
      result = isPerfect(number);
      if(result)
          System.out.println(number +
                  " is a perfect number.");
      else
          System.out.println(number +
                  " is not a perfect number");

      // close Scanner class object
      scan.close();
   }
}

The output of the different test-cases:-

Enter an integer number:: 6
6 is a perfect number.

Enter an integer number:: 12
12 is not a perfect number

Enter an integer number:: 28
28 is a perfect number.

Optimization

This program completely depends on finding factors of the number. We should write such a code that finds factors (except itself) and gives better performance in finding the factors.

In the previous post find factors of a number, we have discussed how to write a method to find factors of a number quickly and give better performance. In the below method we used it.

// check the number is perfect number or not
public static boolean isPerfect(int num) {

   // declare variables
   int sum_of_factors = 0;

   // find factors of the number
   for(int i=1; i&lt;= Math.sqrt(num); i++) {

      // if number is divisible by i
      if(num % i == 0) {
         sum_of_factors += i;

         // don't add number itself
         // and sqrt(num) second times
         if( (i != 1) && ((num/i) != Math.sqrt(num)) ){

            // add factor in sum_of_factors
            sum_of_factors += (num/i);
         }
      }
   }

   // compare sum_of_factors and number
   return (sum_of_factors == num);
}

To check the perfect number we should not add the number itself so, the above method don’t add (num/i) value when the number i==1 because num/i will give num i.e. num/1 = num

Similarly, we should not add the sqrt(num) value for the second time. If the sqrt(num) is the factor of the number then it will be added to sum_of_digits because num%i == 0. But the num/i will also give the same number, and it should be added into the sum_of_factors. Hence, we had written the condition as,

/* Except number itself
 * and sqrt(num) add remaining factors 
 * which is greater than sqrt(num) 
 */

if( (i != 1) && ((num/i) != Math.sqrt(num)) ){
   // add factor in sum_of_factors
   sum_of_factors += (num/i);
}

We will use this optimized solution to find the perfect number in a given range.

Java Program to find the perfect number in a range

Using loops we can find all perfect numbers which belong to a given range.

import java.util.Scanner;

public class PerfectNumberInRange {

   // Check the number is perfect number or not
   public static boolean isPerfect(int num) {

      // declare variables
      int sum_of_factors = 0;

      // find factors of the number
      for(int i=1; i<= Math.sqrt(num); i++) {
        if(num % i == 0) {
          sum_of_factors += i;

          // don't add number itself
          // and sqrt(num) second times
          if( (i != 1) && ((num/i) != Math.sqrt(num)) ){
             // add remaining factors
             sum_of_factors += (num/i);
          }
        }
      }

      // compare sum_of_factors and number
      return (sum_of_factors == num);
   }

   public static void main(String[] args) {

      // declare variables
      int minRange = 0, maxRange = 0;

      // create Scanner class object &amp; read inputs
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter min value of range:: ");
      minRange = scan.nextInt();
      System.out.print("Enter max value of range:: ");
      maxRange = scan.nextInt();

      // check number 
      System.out.println("The perfect numbers from "+
             minRange+" to "+ maxRange+" are:: ");
      for(int i=minRange; i<=maxRange; i++) {
          if(isPerfect(i))
             System.out.print(i+" ");
      }

      // close Scanner class object
      scan.close();
   }
}

Output for the different test-cases:-

Enter min value of range:: 0
Enter max value of range:: 100
The perfect numbers from 0 to 100 are::
0 1 6 28

Enter min value of range:: 1
Enter max value of range:: 1000
The perfect numbers from 1 to 1000 are::
1 6 28 496

Enter min value of range:: 100
Enter max value of range:: 1000000
The perfect numbers from 100 to 1000000 are::
496 8128

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *