Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Perfect Number in Java

Last Updated on May 17, 2023 by Prepbytes

In mathematics, a perfect number is a positive integer that, excluding the original value, equals the sum of all of its positive divisors.

For instance, the integers 1, 2, and 3 equally divide the positive integer 6. We will nevertheless include the number in the list of divisors even though we are aware that it is also divisible on its own. These divisors add up to 6, the same as the number we have been thinking about (1 + 2 + 3 = 6). 6 is, therefore, a perfect number.

What is the Perfect Number in Java?

Except for the number itself, the sum of the proper positive divisors of a perfect number is an integer. Here is one example,

Input: n = 6
Proper divisors of 6 are 1, 2, 3
Sum of its proper divisors = 1 + 2 + 3 = 6
Hence 6 is a perfect number.

Algorithm to Find Perfect Number in Java

  • Insert an integer from the user.
  • Set the initial value of a different variable to 0 to store the sum of the appropriate positive divisors.
  • Check each number from 1 to n/2 to see if it is a divisor. Count the sum of all the divisors. If the sum is exactly n, the number is a perfect number; otherwise, it is not.

Program to Find Perfect Number in Java

There are three ways to find the perfect number in Java:

  • Using for Loop
  • Using while Loop
  • Using recursion in Java

Method 1: Perfect Number in Java Using For Loop

In this method, we will write a Java program that accepts an integer input from the user and checks whether the given number is a perfect number or not.

Code Implementation

class PerfectNumberChecker {
    
    public static boolean isPerfectNumber(int number) {
        int sum = 0;
        
        for (int i = 1; i < number; i++) {
            if (number % i == 0) {
                sum += i;
            }
        }
        
        return sum == number;
    }
    
    public static void main(String[] args) {
        int number = 28; 
        
        if (isPerfectNumber(number)) {
            System.out.println(number + " is a perfect number.");
        } else {
            System.out.println(number + " is not a perfect number.");
        }
    }
}

Output

28 is a perfect number.

Explanation: In this program, the isPerfectNumber method takes an integer number as an argument and checks whether it is a perfect number. The method iterates from 1 to number – 1 and calculates the sum of the divisors of the number (excluding number itself) by checking if the number is divisible by i. If the sum is equal to the number, the method returns true; otherwise, it returns false.

Method 2: Perfect Number in Java Using a While Loop

In this method, we will use a while loop to check whether the given number is a perfect number or not.

Code Implementation

class PerfectNumberChecker {
    
    public static boolean isPerfectNumber(int number) {
        int sum = 0;
        int divisor = 1;
        
        while (divisor < number) {
            if (number % divisor == 0) {
                sum += divisor;
            }
            divisor++;
        }
        
        return sum == number;
    }
    
    public static void main(String[] args) {
        int number = 28; // Replace with the number you want to check
        
        if (isPerfectNumber(number)) {
            System.out.println(number + " is a perfect number.");
        } else {
            System.out.println(number + " is not a perfect number.");
        }
    }
}

Output

28 is a perfect number.

Explanation: In this program, the isPerfectNumber method takes an integer number as an argument and checks whether it is a perfect number. The method initializes sum and divisor to 0 and 1, respectively. It enters a while loop that continues until the divisor is less than number. Inside the loop, it checks if a number is divisible by a divisor, and if so, it adds the divisor to the sum. Then, it increments the divisor by 1. After the loop, the method checks whether the sum is equal to the number and returns the result.

Method 3: Perfect Number in Java Using Recursion

In this method, we will use a recursive method to check whether the given number is a perfect number or not.

Code Implementation

class PerfectNumberChecker {
    
    public static boolean isPerfectNumber(int number) {
        int sum = calculateDivisorSum(number, number / 2);
        return sum == number;
    }
    
    public static int calculateDivisorSum(int number, int divisor) {
        if (divisor == 1) {
            return 1;
        }
        
        if (number % divisor == 0) {
            return divisor + calculateDivisorSum(number, divisor - 1);
        } else {
            return calculateDivisorSum(number, divisor - 1);
        }
    }
    
    public static void main(String[] args) {
        int number = 28; // Replace with the number you want to check
        
        if (isPerfectNumber(number)) {
            System.out.println(number + " is a perfect number.");
        } else {
            System.out.println(number + " is not a perfect number.");
        }
    }
}

Output

28 is a perfect number.

Explanation: In this program, the isPerfectNumber method takes an integer number as an argument and checks whether it is a perfect number. It calls the calculateDivisorSum method, passing number and number/2 as arguments. The calculateDivisorSum method is a recursive method that calculates the sum of divisors of a number starting from divisor and adds the current divisor to the sum if it is a divisor of number. The recursion terminates when the divisor becomes 1. The method returns the calculated sum.

Conclusion
In conclusion, we explored three different approaches to determine whether a given number is a perfect number in Java.

The first approach used a for loop to iterate through all possible divisors of the number. By summing up the divisors and comparing the result with the original number, we were able to determine whether it is a perfect number. This approach provided a straightforward and easily understandable solution.

The second approach utilized a while loop to iteratively calculate the sum of the divisors. Starting with a divisor of 1, we incremented it until it reached the given number. Divisors that evenly divided the number were added to the sum. The final sum was then compared with the original number to determine perfection. This approach demonstrated the flexibility of using a loop construct to solve the problem.

The third approach involved recursion, where a method was called recursively to calculate the sum of the divisors. By dividing the number by 2 and recursively calling the method with a reduced divisor, we were able to compute the sum. This approach showcased the power of recursion to solve the problem in an elegant and concise manner.

Regardless of the approach chosen, all three methods were capable of determining whether a number is perfect. The selection of an approach depends on the specific requirements of the program and personal coding style preferences.

FAQ Related to Perfect Number in Java

Q1. Can you provide an example of a perfect number?
Ans. Yes, the number 6 is a perfect number. Its proper divisors are 1, 2, and 3, and their sum is equal to 6.

Q2. How can I determine if a number is a perfect number in Java?
Ans. You can determine if a number is perfect by calculating the sum of its proper divisors and comparing it with the original number. If they are equal, the number is perfect.

Q3. How does the for loop approach work?
Ans. In the for loop approach, you iterate through all possible divisors of the number using a for loop. By summing up the divisors and comparing the result with the original number, you can determine whether it is a perfect number.

Q4. What is the advantage of using a while loop approach?
Ans. The while loop approach allows you to iteratively calculate the sum of the divisors. This approach is flexible and can handle a variable number of divisors based on the given number.

Q5. What is recursion, and how does it relate to finding perfect numbers?
Ans. Recursion is a programming technique where a method calls itself. In the context of finding perfect numbers, you can use recursion to calculate the sum of the divisors by repeatedly calling the method with reduced divisors. It provides an elegant and concise solution to the problem.

Q6. Are there any limitations to finding perfect numbers in Java?
Ans. Finding perfect numbers in Java is limited by the maximum value of the data types used to represent numbers. For extremely large numbers, the calculations may take a significant amount of time and computational resources.

Leave a Reply

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