×

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

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.