×

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally, a Java application will be written to find every perfect integer inside the specified range. Java coding exams and educational courses usually inquire about the perfect number application.

What is Perfect Number in Java

A perfect number in java is a number in which all the factors of that number are combined or added, then the result would be the number itself. Mathematically, the sum of all the positive factors of a number except the number itself must be equal to the number.

Let’s see how it works with a small example

Consider a small number 6

The factors of 6 include 1,2,3 and the number 6 itself.

Now let’s sum up the factors except the number

1+2+3=6

As we can observe the above example the sum of 1,2,3 would be mathematically be equal to 6 and they are also the factors of 6.

Thus, it can be said that the number 6 is the perfect number.

Similarly, there exit many perfect numbers like 28, 496, 8128 and many others.

Now let us understand the algorithm or a method of finding the perfect numbers in general

How to find the perfect number

Step 1: Begin or read a value (a).

Step 2: Set another variable (m) to store summation.

Step 3: Using the loops find out all the factors of the given value (a).

Step 4: Compute the sum and store the sum value in (m).

Step 5: Now compare both the values (a) and (m).

  1. If the values are equal, then (a) is said to be the perfect number.
  2. Else the value (a) is not regarded as perfect number.

Ways to find a perfect number in Java

The below are the following techniques for finding the perfect number in java. They include

  • By Method
  • By While Loop
  • By Recursion

By Method Technique

The below program depicts how to verify whether a number is perfect number or not by using the methods that perform the specified operation for verification.

File name: PerfNum.java

import java.util.Scanner; // Scanner helps in taking input dynamically 
public class PerfNum  //  name of the class
{  
static long perfect(long n)  // name of the method
{  
long s=0;  // Initially setting the sum as zero
for(int i=1; i <= n/2; i++)  
{  
if(n % i == 0)  
{  
s=s+ i;  // storing the sum of factors 
} 
}  
return s;   //returning the sum
} // End of the method
public static void main(String args[])    
{  
long num, m;  
Scanner sc=new Scanner(System.in);         
System.out.print("Enter the number: ");  
num=sc.nextLong();  // Takes a  number as input from the user
m = perfect(num); // calling the method  
if(m==num)  // comparing the m and num 
System.out.println(num+" is a perfect number");  
else  
System.out.println(num+" is not a perfect number");   
}   
}  

Output

Enter the number: 28
28 is a perfect number
Enter the number: 7
7 is not a perfect number

By While Loop Technique

The below program depicts how to verify whether a number is perfect number or not by using the while loop that helps in performing the specified operation for verification.

File name: PerfNum1.java

import java.util.Scanner;  // Enables in taking the input dynamically
public class PerfNum1  // name of the class
{  
public static void main(String args[])    
{  
long n, s=0;  
Scanner sc=new Scanner(System.in);         
System.out.print("Enter the number: ");  
n=sc.nextLong(); // Taking a number as input from user 
int i=1;  
while(i <= n/2)  // Begin of while loop
{  
if(n % i == 0)  
{  
s= s+ i;  
} 
i++; // Incrementing the value
} // End of While
if(s==n)  //Comparing the n and s
{  
System.out.println(n+" is a perfect number.");  
} 
else  
System.out.println(n+" is not a perfect number.");   
}  
}  

Output

Enter the number: 15
15 is not a perfect number.
Enter the number: 496
496 is a perfect number.

By using Recursion method

The below program depicts how to verify whether a number is perfect number or not by using the recursion technique that helps in performing the specified operation for verification.

File name: PerfNum2.java

import java.util.Scanner;  
public class PerfNum2 
{     
static long s=0;    
long perfect(long n, int i)  
{  
if(i <= n/2)  
{  
if(n% i ==0)  
{  
s=s + i;  
}  
i++;  
perfect(n, i);  
}  
return s;   
}  
public static void main(String args[])    
{  
long num, m;  
int i=1;  
Scanner sc=new Scanner(System.in);         
System.out.print("Enter the number: ");  
num=sc.nextLong();  
PerfNum2 p=new PerfNum2( );  
m = p.perfect(num, i);  
if(m == num)  
System.out.println(num+" is a perfect number");  
else  
System.out.println(num+" is not a perfect number");   
}   
}  

Output

Enter the number: 25
25 is not a perfect number
Enter the number: 6
6 is a perfect number

Related Topics

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.