×

Perfect Number Program in Java

Perfect Number Program in Java

A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a perfect number. This is because all the factors of the number 28, excluding the number itself are: 1, 2, 4, 7, 14, and their sum is 1 + 2 + 4 + 7 + 14 = 28. The perfect number program in Java checks whether the given is the perfect number or not.

The steps required to find the perfect are as follows:

Step 1: Declare a variable x.

Step 2: Take input from the user and assign it to the variable x.

Step 3:  Declare another variable sumOfFactors. Assign value zero to it, i.e., sumOfFactors = 0.

Step 4: Find all the factors of x, barring x itself.

Step 5: Store the sum of all factors found in step 3, in the variable sumOfFactors.

Step 6: Compare sumOfFactors and x to check whether they are equal or not; if they are equal, the input number is perfect number; otherwise, not.

There are two ways to implement the above steps: one is iterative, and another is recursive. Let’s start with the iterative approach.

Iterative Approach

Filename: PerfectNumber.java

// importing the Scanner class
import java.util.Scanner;
public class PerfectNumber
{
public static void main(String argvs[])
{
    int x; // contains the number given by the user
    // creating an object of the Scanner class
    Scanner scr = new Scanner(System.in);
    System.out.println("Enter a number " );
    x = scr.nextInt(); // reading input from the user
    int sumOfFactors = 0; // storing the sum of the factors of the input number
    // loop for finding the factors of
    // the given number other than itself
    for(int i = 1; i <= x / 2; i++)
    {
        if(x % i == 0)
        {
            // factor found!
            // doing the summation of factors
            sumOfFactors = sumOfFactors + i;
        }
    }
    // displaying the outcome
    if(x == sumOfFactors)
    {
        System.out.println("Entered number " + x + " is a perfect number. " );
    }
    else
    {
        System.out.println("Entered number " + x + " is not a perfect number. " );       
    }
}
} 

Output 1:

 Enter a number
6
Entered number 6 is a perfect number. 

Output 2:

 Enter a number
15
Entered number 15 is not a perfect number. 

Explanation:  In the above code, we are storing the input from the user in the variable x. Then, using the Java for-loop, we are finding the factors of x. The iterations start from 1 and go till x / 2. This way, we are excluding the number x from the factors. Every number from 1 to x / 2 is checked for the factors of x. If the factor is found, that factor is added to the variable sumOfFactors. Eventually, we are checking the sumOfFactors with x and displaying the result accordingly.

Recursive Approach

Filename: PerfectNumber1.java

 // importing the Scanner class
import java.util.Scanner;
public class PerfectNumber1
{
static int sumOfFactors = 0; // storing the sum of the factors of the input number
// Method for finding and adding factors of the input number
public static void perfectNoFactors(int n, int i)
{
    // handling base case
    if(i > n / 2)
    {
        return;
    }
    if( n % i == 0 )
    {
        // factor found!
        // adding the factors of the variable sumOfFactors
        sumOfFactors = sumOfFactors + i;
    }
    // recursively searching for factors
    perfectNoFactors(n, i + 1);
}
public static void main(String argvs[])
{
    int x; // contains the number given by the user
    // creating an object of the Scanner class
    Scanner scr = new Scanner(System.in);
    System.out.println("Enter a number " );
    x = scr.nextInt(); // reading input from the user
    perfectNoFactors(x, 1); // calling the method perfectNoFactors
    // displaying the result
    if(sumOfFactors == x)
    {
        System.out.println("Entered number " + x + " is a perfect number. " );
    }
    else
    {
        System.out.println("Entered number " + x + " is not a perfect number. " );
    }
}
} 

Output1:

 Enter a number
6
Entered number 6 is a perfect number. 

Output2:

 Enter a number
7
Entered number 7 is not a perfect number. 

Explanation: Instead of Java for-loop, we have relied upon the recursive call to find the factors of x. The approach still remains the same, i.e., to check every number between 1 and x / 2 in order to get the factors of x, excluding x itself.

To find perfect numbers between 1 to 500

The following Java program displays perfect numbers present between 1 to 500.

Filename: PerfectNumber2.java

 public class PerfectNumber2
{
private static Boolean isPerfectNo(int n)
{
    // for containing sum of the factors of number n
    int sum = 0;
    //loop for finding factors till n/2
    for(int i =  1; i <= n / 2; i++)
    {
        if(n % i == 0)
        {
            // Factor found!
            // Updating sum
            sum = sum + i;
        }
    }
    Boolean isEqual;
    // checking whether n is equal to sum or not
    isEqual = (n == sum) ? true : false;
    //returning the result
    return isEqual;
}
// main method
public static void main(String argvs[])
{
    int no = 500; // till 500, we are finding the perfect numbers
    // loop for finding pefect number from 1 till 500
    for(int i = 1; i <= no; i++)
    {
        if(isPerfectNo(i)) // calling the method isPerfectNo()
        {
            // Displaying the perfect numbers from 1 to 500
            System.out.println(i + " is a prefect number");
        }
    }
}
} 

Output:

 6 is a perfect number
28 is a perfect number
496 is a perfect number 

Explanation: In the main method, the Java for-loop is iterating from 1 to 500. In each iteration, we are calling the method isPerfectNo(), whose return type is Boolean. The method takes a number (n) in its argument and checks whether that number, n, is a perfect number or not. If n is a perfect number, the method returns true; otherwise, false. For those numbers, where the method isPerfectNo() has returned false, are discarded, and the rest of the numbers are printed on the console.


Related Topics

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.