Finding Perfect Number in Java: A Complete Guide
Updated on May 28, 2025 | 13 min read | 6.34K+ views
Share:
For working professionals
For fresh graduates
More
Updated on May 28, 2025 | 13 min read | 6.34K+ views
Share:
Table of Contents
Did You Know? Perfect numbers have been known since ancient Greek times. Mathematicians like Euclid and Euler made significant contributions to understanding perfect numbers. Euclid proved that if 2𝑝−1 is prime, then 2𝑝−1(2𝑝−1) is a perfect number. These are now called Euclid-Euler perfect numbers.
A perfect number in Java is a positive integer that is equal to the sum of its proper divisors, excluding the number itself. The smallest perfect number is 6, which is divisible by 1, 2, and 3, and the sum of these divisors, 1 + 2 + 3, equals 6. In Java, discovering a perfect number involves writing an algorithm that checks if a given number satisfies this condition.
In this blog, you will learn how to identify a perfect number in Java through practical examples. We’ll also walk you through step-by-step instructions to create a Java program that efficiently calculates whether a number is perfect.
Want to learn how to implement the Perfect Number algorithm in Java? Join upGrad’s Online Software Development Courses and specialize in Cyber Security, Full Stack Development, Game Development, etc. With an updated Generative AI curriculum and training in the latest programming tools and languages, you’ll have access to all the information to excel in the tech industry.
A perfect number in mathematics is a positive integer equal to the sum of its proper divisors, excluding itself. For example, 6 is perfect because 1, 2, and 3 add up to 6, and 28 is perfect since 1, 2, 4, 7, and 14 sum to 28. These numbers have a rich history, especially in ancient Greek mathematics. Mathematicians like Euclid and Pythagoras studied them, paving the way for advances in number theory.
Perfect numbers aren’t just curiosities, they’re deeply tied to the foundations of number theory. One key link is with Mersenne primes, special prime numbers that help generate perfect numbers through a fascinating formula discovered by Euclid. This connection reveals patterns and mysteries that continue to intrigue mathematicians today.
In 2025, excelling at programming concepts like identifying the perfect number in Java will set you apart in data analytics roles and enhance your career. If you’re ready to sharpen your coding and analytical skills, explore these top-rated courses designed to help you excel in data-driven business solutions.
Perfect numbers play a key role in the Euclid-Euler Theorem, linking them to Mersenne primes—primes expressed as 2ⁿ−1. This connection isn’t just historical; it’s practical because it provides a formula to quickly generate or identify perfect numbers without checking every divisor.
By focusing on Mersenne primes, mathematicians can efficiently find perfect numbers, saving time and computational effort. This approach makes perfect number detection much faster than testing each number individually.
With this mathematical foundation in place, you’re ready to see how these concepts translate into Java code, turning theory into a practical program that can efficiently assist in identifying and finding perfect numbers in Java.
To understand a perfect number in Java more clearly, it's essential to break down the concept of divisors and the sum of divisors.
Example:
For the number 6:
Since the sum of the proper divisors of 6 equals 6 itself, 6 is a perfect number.
Also Read: Java Servlets by Example: Lifecycle, Practical Implementations, and Best Practices (2025)
Now, let’s explore some well-known examples of the perfect number in Java to help visualize the concept and understand how it fits into number theory.
Perfect Number | Proper Divisors | Sum of Proper Divisors | Is Perfect?
|
---|---|---|---|
6 | 1, 2, 3 | 6 | Yes |
28 | 1, 2, 4, 7, 14 | 28 | Yes |
496 | 1, 2, 4, 8, 16, 31, 62, 124, 248 | 496 | Yes |
Connection with Mersenne Primes
Understanding Mersenne primes deepens the theory behind perfect numbers and offers practical benefits when coding in Java. By focusing on Mersenne primes, a program can skip unnecessary checks and directly generate perfect numbers using the Euclid-Euler formula, making the process faster and more efficient. This approach allows you to precompute or quickly verify perfect numbers, streamlining your Java implementation.
Specifically:
For example:
Looking to excel at full-stack development with a focus on AI? upGrad’s AI-Driven Full-Stack Development bootcamp teaches you how to create intelligent Java applications, harnessing the power of OpenAI, GitHub Copilot, Bolt AI, and more. Unlock the perfect balance between code and AI to build next-level software!
With a solid grasp of what defines a perfect number in Java and its mathematical roots, it’s time to use Java to spot them efficiently.
In this section of the article, we’ll explore 5 distinct Java techniques, from brute-force checks to optimized methods utilizing math theory, recursion, and divisor pairing, showcasing efficient ways to identify perfect numbers. Each approach is designed to demonstrate a unique way of solving the problem while maintaining efficiency and clarity.
Both the for loop and while loop can be used to check divisors from 1 up to num - 1, summing divisors to determine if the number is perfect. The core logic remains the same; the only difference is the loop structure, for it uses a predefined range, while the while loop continues until the condition fails.
For Loop Example:
for (int i = 1; i < num; i++) {
if (num % i == 0) sum += i;
}
Output:
28 is a perfect number.
While Loop Example:
int i = 1;
while (i < num) {
if (num % i == 0) sum += i;
i++;
}
Output:
28 is a perfect number.
Explanation:
Both approaches yield the same result: checking if the sum equals the number to confirm it’s perfect, offering flexibility in coding style without changing performance.
This method improves the efficiency by reducing the range of possible divisors. Since no divisor of 𝑛𝑢𝑚 can be greater than 𝑛𝑢𝑚/2, this method eliminates unnecessary checks and speeds up the process.
Code Example:
public class PerfectNumber {
public static boolean isPerfectNumber(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
public static void main(String[] args) {
int[] testNumbers = {6, 10, 496};
for (int num : testNumbers) {
if (isPerfectNumber(num)) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
}
}
}
Output:
6 is a perfect number.
10 is not a perfect number.
496 is a perfect number.
Explanation:
By limiting the divisor checks to num/2, this method avoids needless iterations over numbers that can’t possibly divide num. Testing multiple values demonstrates how the logic distinguishes perfect numbers like 6 and 496 from non-perfect numbers such as 10.
This approach refines Method 2 by moving the divisor-summing logic into a separate helper function. It keeps the core logic the same, checking divisors up to num/2, but improves code readability and reusability by making it modular.
Code Example:
public class PerfectNumber {
// Helper function to calculate sum of divisors up to num/2
public static int sumOfDivisors(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum;
}
// Main method uses the helper function to check for perfect number
public static boolean isPerfectNumber(int num) {
return sumOfDivisors(num) == num;
}
public static void main(String[] args) {
int[] testNumbers = {496, 45}; // 496 is perfect, 45 is not
for (int num : testNumbers) {
if (isPerfectNumber(num)) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
}
}
}
Output:
496 is a perfect number.
45 is not a perfect number.
Explanation:
This refactoring doesn’t change the core logic but organizes the code better by separating concerns. It makes the program easier to maintain, test, and extend, key principles in clean coding, without sacrificing performance.
Recursion provides an elegant way to find divisors. The logic is similar to looping, but we break the process down into smaller, self-similar calls. This approach demonstrates how recursion can simplify the problem.
Code Example:
public class PerfectNumber {
// Recursive method to sum divisors
public static int sumDivisors(int num, int divisor) {
if (divisor == 0) {
return 0;
}
if (num % divisor == 0) {
return divisor + sumDivisors(num, divisor - 1);
} else {
return sumDivisors(num, divisor - 1);
}
}
// Check if number is perfect
public static boolean isPerfectNumber(int num) {
// Sum divisors excluding the number itself
return sumDivisors(num, num / 2) == num;
}
public static void main(String[] args) {
int[] testNumbers = {6, 10, 496};
for (int num : testNumbers) {
if (isPerfectNumber(num)) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
}
}
}
Output:
6 is a perfect number.
10 is not a perfect number.
496 is a perfect number.6 is a perfect number.
10 is not a perfect number.
496 is a perfect number.
Explanation:
The sumDivisors method recursively checks each number from num/2 down to 1, adding divisors of num. The isPerfectNumber method then compares this sum with the original number. Using recursion simplifies the logic by avoiding explicit loops, making the code easier to read and follow while achieving the same goal.
To further optimize the process, we can limit the range of divisors to √𝑛𝑢𝑚. This method utilizes the fact that divisors come in pairs, so if you find a divisor 𝑑, you can automatically find its pair 𝑛𝑢𝑚/𝑑.
Code Example:
int sum = 1; // 1 is always a divisor (except for 1 itself)
int sqrt = (int) Math.sqrt(num);
for (int i = 2; i <= sqrt; i++) {
if (num % i == 0) {
sum += i;
int pairDivisor = num / i;
if (pairDivisor != i) {
sum += pairDivisor;
}
}
}
return sum == num;
}
public static void main(String[] args) {
int num1 = 6;
int num2 = 10;
System.out.println(num1 + (isPerfectNumber(num1) ? " is a perfect number." : " is not a perfect number."));
System.out.println(num2 + (isPerfectNumber(num2) ? " is a perfect number." : " is not a perfect number."));
}
}
Output:
6 is a perfect number.
10 is not a perfect number.
Explanation:
This method drastically cuts down the number of iterations by only looping until the square root. When a divisor is found, both it and its pair are added to the sum. This makes the code more efficient, especially for larger numbers, while still accurately identifying perfect numbers.
Summary: Choosing the Right Method to Find Perfect Numbers in Java
Elevate your front-end development and design expertise with upGrad’s Master of Design in User Experience. This 12-month, AI-powered program equips you with skills to create seamless, user-friendly products, perfectly complementing your Java development knowledge. Learn from design experts at Apple, Pinterest, Cisco, and PayPal, and take your career to the next level.
Understanding what defines a perfect number in Java lays the foundation needed to build a reliable Java program that can accurately identify them. Now, let's explore step-by-step how to implement a perfect number finder.
In this section, we'll guide you through the process of implementing a Perfect Number Finder in Java. This tutorial will take you through clear, step-by-step code implementation and explain the logic behind finding perfect numbers in Java.
Understanding Perfect Numbers
A perfect number equals the sum of its proper divisors, excluding itself, like 6 or 28.
Steps to Implement a Perfect Number Finder in Java
Code Implementation
Below is the code for finding perfect numbers in Java:
import java.util.Scanner;
public class PerfectNumberFinder {
// Method to check if a number is a perfect number
public static boolean isPerfectNumber(int num) {
if (num <= 0) return false; // Reject non-positive numbers
int sum = 0;
// Find divisors and calculate the sum
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
// If the sum of divisors equals the number, it's a perfect number
return sum == num;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter a number to check if it's perfect: ");
int number = scanner.nextInt();
// Check and print the result
if (number <= 0) {
System.out.println("Please enter a positive integer greater than zero.");
} else if (isPerfectNumber(number)) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
scanner.close();
}
}
Explanation:
1. Input Validation: The code now checks if the input number is positive. If the number is zero or negative, it immediately rejects it, prompting the user to enter a positive integer. This prevents invalid or meaningless checks.
2. isPerfectNumber Method:
This validation step improves program robustness, making it safer and more user-friendly for beginners.
2. main Method:
Example Outputs:
1. Input:
Enter a number to check if it's perfect: 496
Output:
496 is a perfect number.
Explanation:
The divisors of 496 include 1, 2, 4, 8, 16, 31, 62, 124, and 248. Their sum equals 496, confirming it as a perfect number.
2. Input:
Enter a number to check if it's perfect: -5
Output:
Please enter a positive integer greater than zero.
Explanation:
Negative numbers and zero are invalid inputs for perfect number checks and are handled gracefully by the program.
3. Input:
Enter a number to check if it's perfect: 4960
Output:
4960 is not a perfect number.
Explanation:
The sum of the proper divisors of 4960 does not equal the number itself, so it is not perfect.
Also Read: How to Reverse a Number in Python?
Kickstart your coding journey with upGrad’s free JavaScript Basics from Scratch course. Learn essential concepts like variables, data types, loops, functions, and event handling to build dynamic web applications. Plus, strengthen your programming foundation by exploring Java alongside JavaScript, giving you a versatile skill set for both web and software development.
Once you understand how to implement a perfect number in Java, the next step is to explore how to make the algorithm that finds them run faster and smarter. Comes. Let’s dive deeper into this.
Identifying a perfect number in Java is a classic problem in number theory. A perfect number is defined as a positive integer that is equal to the sum of its proper divisors (excluding itself). However, when implementing algorithms to check for perfect numbers, the challenge often lies in optimizing performance for large numbers.
In this section of the article, we'll explore 4 techniques for optimizing the perfect number algorithm in Java. We'll focus on improving time complexity and utilizing Java-specific features for better performance.
Both efficient looping and divisor pairing boil down to the same core idea—reduce the number of divisor checks by looping only up to the square root of the number. What sets these concepts apart is the focus:
By combining these, you get a fast and clean approach, checking fewer numbers while counting all divisors accurately.
public class PerfectNumber {
public static boolean isPerfectNumber(int num) {
if (num <= 1) return false;
int sum = 1; // 1 is always a divisor
int sqrt = (int) Math.sqrt(num);
for (int i = 2; i <= sqrt; i++) {
if (num % i == 0) {
sum += i;
int pairedDivisor = num / i;
if (pairedDivisor != i) {
sum += pairedDivisor;
}
}
}
return sum == num;
}
public static void main(String[] args) {
int num = 28;
System.out.println(num + " is perfect: " + isPerfectNumber(num));
}
}
Output:
28 is perfect: true
Explanation:
This single method efficiently finds divisors by stopping at √𝑁 and adding divisor pairs simultaneously, minimizing iterations and redundant checks while accurately detecting perfect numbers.
Also Read: Prime Number Program in Java: How to Print and Check Prime Numbers?
For large numbers, if we find that the sum of divisors exceeds the number, we can terminate the check early. This optimization helps to avoid unnecessary calculations when it's already clear that the number can't be perfect.
Code Example:
public class PerfectNumber {
public static boolean isPerfectNumber(int num) {
if (num <= 1) return false;
int sum = 1; // Start with 1 because it's a divisor
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
sum += i;
if (i != num / i) {
sum += num / i;
}
}
if (sum > num) return false; // Early termination
}
return sum == num;
}
public static void main(String[] args) {
int num = 27;
System.out.println(num + " is perfect: " + isPerfectNumber(num));
}
}
Output:
27 is perfect: false
Explanation:
Here, as soon as the sum exceeds 𝑁, the algorithm terminates and returns false because the number can't be perfect. This optimization is especially useful for very large numbers, speeding up the algorithm by avoiding unnecessary checks.
Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
In real applications, you might need to check many numbers repeatedly, such as scanning a large range for perfect numbers or running the check multiple times in a loop. Recalculating whether each number is perfect can be costly and time-consuming.
Memoization helps by storing previously computed results. So, if the same number appears again, the program can instantly return the stored answer without running the full calculation again. This technique boosts efficiency when working with repeated or overlapping queries.
Code Example:
import java.util.HashSet;
public class PerfectNumber {
private static HashSet<Integer> perfectNumbers = new HashSet<>();
public static boolean isPerfectNumber(int num) {
if (num <= 1) return false;
if (perfectNumbers.contains(num)) {
return true; // Return pre-calculated result
}
int sum = 1;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
sum += i;
if (i != num / i) {
sum += num / i;
}
}
}
if (sum == num) {
perfectNumbers.add(num); // Cache the result
return true;
}
return false;
}
public static void main(String[] args) {
int num = 6;
System.out.println(num + " is perfect: " + isPerfectNumber(num));
System.out.println("Checking again: " + isPerfectNumber(num));
}
}
Output:
6 is perfect: true
Checking again: true
Explanation:
We use a HashSet to store previously calculated perfect numbers, allowing the algorithm to return the result instantly if the number has been checked before. This eliminates redundant calculations and saves time when checking multiple numbers in a sequence.
Also Read: Top 10 Free Java Courses with Certificates for In-Demand Java Jobs
Rather than checking every divisor through iteration, you can use advanced number-theoretic functions to calculate the sum of divisors more efficiently. In mathematics, the sigma function (σ) represents the sum of divisors of a number and can be computed using prime factorization formulas.
While Java doesn’t have built-in sigma functions, you can implement these formulas yourself or use specialized libraries for number theory that handle divisor sums faster than simple loops. This approach reduces computational overhead by utilizing mathematical properties instead of brute-force checks.
Code Example:
if (i != num / i) {
sum += num / i;
}
}
}
return sum;
}
public static boolean isPerfectNumber(int num) {
if (num <= 1) return false;
return sumOfDivisors(num) == num;
}
public static void main(String[] args) {
int num = 496;
System.out.println(num + " is perfect: " + isPerfectNumber(num));
}
}
Output:
496 is perfect: true
Explanation:
The sumOfDivisors function calculates the sum of divisors in an optimized way, limiting the iterations to √𝑁. This efficient summation speeds up the perfect number check, especially for larger numbers.
Looking to deepen your understanding of object-oriented programming with Java? upGrad’s Java Object-Oriented Programming course offers a comprehensive journey through essential concepts like classes, objects, inheritance, polymorphism, encapsulation, and abstraction. With hands-on coding examples and real-world projects, you’ll build practical skills to design and develop robust Java applications confidently.
Understanding what makes a number perfect lays the groundwork to explore how you can identify them programmatically. Let’s move on to see how a Java program can detect perfect numbers and where this finds practical use.
This section focuses on how a Java program for perfect number can be used to identify them, which are equal to the sum of their proper divisors. Understanding how to implement this program helps illustrate key programming concepts such as loops, conditionals, and efficiency.
We’ll also explore practical use cases where detecting perfect numbers is important, including cryptography, numerical analysis, and algorithm optimization.
Java Program to Check a Perfect Number
Let's write a Java program that checks whether a number is perfect:
public class PerfectNumberChecker {
public static boolean isPerfect(int num) {
int sum = 0;
// Calculate sum of divisors
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
// Check if sum equals the number
return sum == num;
}
public static void main(String[] args) {
int number = 28;
if (isPerfect(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:
Also Read: Is Java Easy to Learn? Common Challenges and How to Overcome Them
Generating Perfect Numbers Within a Range
You can also generate all perfect numbers within a specific range. Here's how:
public class PerfectNumberGenerator {
public static boolean isPerfect(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
public static void main(String[] args) {
int limit = 10000;
System.out.println("Perfect numbers up to " + limit + " are:");
for (int i = 1; i <= limit; i++) {
if (isPerfect(i)) {
System.out.println(i);
}
}
}
}
Output:
Perfect numbers up to 10000 are:
6
28
496
8128
Explanation:
Consider adding a simple check to skip 0 and 1 since neither qualifies as a perfect number and can affect test correctness. For example, modify isPerfect to return false for these cases upfront. This ensures the algorithm handles common edge cases cleanly.
Also Read: Top 8 Reasons Why Java is So Popular With Developers in 2025
Practical Applications of Perfect Numbers
1. Cryptography: Perfect numbers are tied to Mersenne primes, which are vital for generating large prime numbers used in encryption.
Example: Large Mersenne primes (of the form 2^p−1) help create secure keys in algorithms like RSA by providing prime numbers that are hard to factor, enhancing data security. Tools like GMP (GNU Multiple Precision Arithmetic Library) utilize such prime checks to handle large numbers efficiently in cryptographic systems.
Also Read: Top 135+ Java Interview Questions You Should Know in 2025
2. Computer Science: Algorithms involving divisor sums or factorization rely on perfect numbers to optimize performance and analyze complexity.
Example: Factoring integers into divisors and understanding their sums is fundamental in cryptanalysis, where breaking down keys requires efficient factorization. This knowledge informs the development of faster algorithms and security assessments in cryptography.
3. Mathematical Puzzles: Perfect numbers serve as classic programming challenges that build foundational skills in loops and conditionals.
Example: Coding exercises that ask learners to check if a number is perfect sharpen their understanding of iteration, modular arithmetic, and condition-based logic—skills essential for algorithm development and problem-solving.
Also Read: Top Java Courses for 2025 – Developer Approved Picks
4. Error Detection: Sum properties similar to those in perfect numbers underpin checksum algorithms used in data integrity verification.
Example: Network protocols calculate checksums by summing byte values, detecting errors during transmission. This process mirrors divisor summation in perfect numbers, showing how mathematical concepts translate into real-world error-checking mechanisms.
5. Educational Tools: Teaching perfect numbers introduces beginners to key programming concepts through practical examples.
Example: Writing code to identify perfect numbers helps beginners learn iteration, divisibility tests, and conditional statements, building a strong foundation for more complex programming tasks.
Now that you’ve learned how to code perfect numbers in Java, let’s see how upGrad’s courses can help you master practical Java skills.
To confidently identify perfect numbers in Java, focus on efficient divisor checks by limiting loops to the square root and using divisor pairing to reduce calculations. Practice various methods, from simple loops to recursion, to enhance coding flexibility. Moreover, challenge yourself with larger inputs and optimize your code for better performance.
If you’re looking to bridge the gap between learning and applying practical applications, upGrad’s courses offer the guidance and hands-on experience you need to advance your career. Whether you’re struggling with a lack of direction or aiming for growth in software development, upGrad provides structured learning paths and expert support to help you master Java and beyond.
While we’ve highlighted top programs, here are additional courses crafted to sharpen your mastery of the perfect number concept in Java. These courses will strengthen your programming skills and deepen your understanding of algorithmic problem-solving in Java.
If you're unsure which career path suits you best, upGrad’s personalized career guidance can provide the clarity and direction you need to move forward confidently. Plus, by visiting any upGrad center, you can jumpstart your journey with hands-on training that builds real-world skills to fast-track your professional growth.
900 articles published
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources