What is a Perfect Number in Python? Exploring the Concept and Python Program to Find Them
By Rohit Sharma
Updated on May 30, 2025 | 26 min read | 13.55K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on May 30, 2025 | 26 min read | 13.55K+ views
Share:
Table of Contents
Did you know? The ancient Greeks, including Pythagoras and Euclid, were the first to study perfect numbers. They believed these numbers held mystical properties and were quite rare. For centuries, only the first four perfect numbers (6, 28, 496, 8128) were known! |
Perfect numbers, where the sum of their proper divisors equals the number itself, have captivated mathematicians since ancient Greece. Euclid's rule for generating even perfect numbers in his Elements highlights their historical significance. Their rarity and unique properties continue to intrigue number theorists today.
Python programming offers an excellent avenue to explore these fascinating entities. Implementing checks for perfect numbers provides hands-on experience with fundamental concepts like loops, conditionals, and efficient algorithm design, fostering computational problem-solving skills.
This discussion explores diverse Python programming methodologies for identifying these intriguing entities. We'll explore different approaches, from straightforward implementations using basic arithmetic and loop structures to more optimized techniques that enhance computational efficiency.
Ready to level up your Python skills and tech career? upGrad’s software development courses feature a Generative AI curriculum and specializations in Cyber Security, Full-Stack Development, and Game Development—preparing you for in-demand roles!
Perfect numbers, in the realm of mathematics, are positive integers that hold a unique property: they are equal to the sum of their proper positive divisors (excluding the number itself). For instance, consider the number 6.
Its proper divisors are 1, 2, and 3; their sum (1 + 2 + 3) equals 6, making it a perfect number. Another example is 28, whose proper divisors are 1, 2, 4, 7, and 14, and their sum (1 + 2 + 4 + 7 + 14) is also 28. These intriguing numbers have fascinated mathematicians for centuries. These intriguing numbers have captivated mathematicians for centuries, and it's worth noting that all known perfect numbers are even and are intimately connected to Mersenne primes.
Ready to elevate your technical skills? upGrad's expertly crafted programs are your gateway to mastering the world of tech:
Finally, before determining if a number is perfect, we need to identify all its divisors, specifically its proper ones.
The first crucial step is identifying a number's proper divisors to determine if it is perfect. Proper divisors are all the positive integers that divide the number evenly, excluding the number itself.
For instance, to find the proper divisors of 10:
Therefore, the proper divisors of 10 are 1, 2, and 5.
To find the proper divisors of a number programmatically, we can employ a loop. The core idea is to iterate through potential divisors and check for divisibility. Here's a pseudocode representation of the divisor-checking logic:
function find_proper_divisors(number):
divisors = []
for i from 1 to (number / 2): // Iterate from 1 up to half the number
if number is divisible by i: // Check for no remainder
add i to divisors
return divisors
This approach efficiently identifies all proper divisors by checking only up to half the number, as any divisor greater than half would have a corresponding smaller divisor already found.
Intrigued by the blend of math and code? Take your expertise further. The Generative AI Foundations Certificate Program by upGrad offers a comprehensive journey into the exciting world of artificial intelligence, equipping you with in-demand skills to build innovative solutions.
Also Read: Machine Learning Projects with Source Code in 2025
Now that we've grasped the theoretical concept of perfect number in python, let's shift our focus to the practical application of this knowledge.
Perfect number in Python are those fascinating integers that equal the sum of their proper divisors (excluding the number itself). Identifying them in Python provides an excellent opportunity to practice fundamental programming concepts such as loops, conditional statements, and list comprehension while exploring algorithm optimization.
Python's clear syntax and in-built functionalities are well-suited for implementing efficient solutions. This section will explore several Pythonic approaches to finding perfect numbers, ranging from straightforward methods to more optimized techniques, culminating in discussing the most efficient strategies.
This method employs a straightforward iterative process using a ‘for’ loop to find all proper divisors of a given number. It then calculates the sum of these divisors and checks if it matches the original number.
def is_perfect(n):
"""Check if a number is perfect using a basic for loop."""
if n < 2:
return False # 1 is not considered a perfect number
sum_divisors = 0
for i in range(1, n):
if n % i == 0:
print(f"Divisor found: {i}")
sum_divisors += i
print(f"Sum of divisors (excluding {n}): {sum_divisors}")
return sum_divisors == n
# Test cases
print("Is 6 perfect?", is_perfect(6)) # Output: True
print("Is 28 perfect?", is_perfect(28)) # Output: True
print("Is 10 perfect?", is_perfect(10)) # Output: False
Output:
Divisor found: 1
Divisor found: 2
Divisor found: 3
Sum of divisors (excluding 6): 6
Is 6 perfect? True
Divisor found: 1
Divisor found: 2
Divisor found: 4
Divisor found: 7
Divisor found: 14
Sum of divisors (excluding 28): 28
Is 28 perfect? True
Divisor found: 1
Divisor found: 2
Divisor found: 5
Sum of divisors (excluding 10): 8
Is 10 perfect? False
Explanation:
This method uses a straightforward loop to find all divisors of n below it and add them. When this sum equals n, a perfect number results.
List comprehension offers a more Pythonic and often more readable way to create lists based on existing iterables. In this context, it can generate the list of proper divisors in a single line.
def is_perfect(n):
"""Check if a number is perfect using list comprehension."""
if n < 2:
return False
divisors = [i for i in range(1, n) if n % i == 0]
print(f"Divisors of {n}: {divisors}")
return sum(divisors) == n
# Test cases
print("Is 6 perfect?", is_perfect(6)) # Output: True
print("Is 28 perfect?", is_perfect(28)) # Output: True
print("Is 12 perfect?", is_perfect(12)) # Output: False
Output:
Divisors of 6: [1, 2, 3]
Is 6 perfect? True
Divisors of 28: [1, 2, 4, 7, 14]
Is 28 perfect? True
Divisors of 12: [1, 2, 3, 4, 6]
Is 12 perfect? False
Explanation:
The is_perfect_list_comprehension function checks for perfect numbers. The core logic lies in the list comprehension [i for i in range(1, n) if n % i == 0].
This concisely creates a list named divisors containing all numbers i in the range 1 to n-1 for which n is divisible by i. The function returns True if the sum of the elements in the divisors list equals n.
Python's built-in filter() function provides a functional way to filter elements from an iterable based on a given function. We can use it with a lambda function to select the proper divisors.
def is_perfect(n):
"""Check if a number is perfect using filter and lambda."""
if n < 2:
return False
divisors = list(filter(lambda x: n % x == 0, range(1, n)))
print(f"Divisors of {n}: {divisors}")
return sum(divisors) == n
# Test cases
print("Is 6 perfect?", is_perfect(6)) # Output: True
print("Is 28 perfect?", is_perfect(28)) # Output: True
print("Is 20 perfect?", is_perfect(20)) # Output: False
Output:
Divisors of 6: [1, 2, 3]
Is 6 perfect? True
Divisors of 28: [1, 2, 4, 7, 14]
Is 28 perfect? True
Divisors of 20: [1, 2, 4, 5, 10]
Is 20 perfect? False
Explanation:
Using filter(), this approach functionally extracts divisors from a range, summing them to determine perfection.
While typically not the most efficient approach for this problem due to potential recursion depth limitations for larger numbers, recursion offers an alternative perspective on calculating the sum of divisors.
def sum_of_divisors_recursive(n, i=None, current_sum=0):
"""Recursively calculates the sum of proper divisors of n."""
if i is None:
i = n // 2 # Start from n // 2, the largest possible proper divisor
if i < 1:
return current_sum
if n % i == 0:
current_sum += i
return sum_of_divisors_recursive(n, i - 1, current_sum)
def is_perfect_recursive(n):
"""Determines if a number is perfect using recursive sum calculation."""
if n < 2:
return False
return sum_of_divisors_recursive(n) == n
# Test cases
print("Is 6 perfect?", is_perfect_recursive(6)) # Output: True
print("Is 28 perfect?", is_perfect_recursive(28)) # Output: True
print("Is 18 perfect?", is_perfect_recursive(18)) # Output: False
Output:
Is 6 perfect? True
Is 28 perfect? True
Is 18 perfect? False
Explanation:
The sum_of_divisors_recursive function takes three arguments:
The base case is when i becomes less than 1, at which point the function returns the accumulated current_sum. If i divides n evenly, it is added to current_sum. The function then recurses by decrementing i by 1.
The is_perfect_recursive function starts the recursion and compares the final sum to n. If they are equal, the number is perfect. This elegant recursive approach demonstrates a clear divide-and-conquer logic for summing divisors.
We can significantly optimize the finding of divisors by realizing that if i is a divisor of n, then n/i is also a divisor. We only need to iterate up to the square root of n.
def is_perfect(n):
"""Check if a number is perfect using optimized divisor search up to sqrt(n)."""
if n < 2:
return False
sum_divisors = 1 # 1 is a divisor of all integers > 1
print(f"Checking divisors for {n} up to sqrt({n})")
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
pair = n // i
sum_divisors += i
if i != pair:
sum_divisors += pair
print(f"Divisor pair found: {i} and {pair}")
print(f"Sum of divisors (excluding {n}): {sum_divisors}")
return sum_divisors == n
# Test cases
print("Is 6 perfect?", is_perfect(6)) # Output: True
print("Is 28 perfect?", is_perfect(28)) # Output: True
print("Is 496 perfect?", is_perfect(496)) # Output: True
print("Is 500 perfect?", is_perfect(500)) # Output: False
Output:
Checking divisors for 6 up to sqrt(6)
Divisor pair found: 2 and 3
Sum of divisors (excluding 6): 6
Is 6 perfect? True
Checking divisors for 28 up to sqrt(28)
Divisor pair found: 2 and 14
Divisor pair found: 4 and 7
Sum of divisors (excluding 28): 28
Is 28 perfect? True
Checking divisors for 496 up to sqrt(496)
Divisor pair found: 2 and 248
Divisor pair found: 4 and 124
Divisor pair found: 8 and 62
Divisor pair found: 16 and 31
Sum of divisors (excluding 496): 496
Is 496 perfect? True
Checking divisors for 500 up to sqrt(500)
Divisor pair found: 2 and 250
Divisor pair found: 4 and 125
Divisor pair found: 5 and 100
Divisor pair found: 10 and 50
Divisor pair found: 20 and 25
Sum of divisors (excluding 500): 592
Is 500 perfect? False
Explanation:
This method significantly optimizes performance by reducing the range of checks up to root of n. For every divisor i found, its corresponding pair n // i is also a divisor (unless i is the square root of n). This dramatically improves performance for large numbers, making it an O(root-n) approach, which is far more efficient than the previous O(n) methods.
For beginners, the basic loop-based approach is often the easiest to grasp. List comprehension offers a more Pythonic and readable solution for those familiar with it. However, the optimized root n method is undoubtedly the superior choice for maximum efficiency, especially when dealing with large numbers.
Fascinated by the logic of perfect numbers and the power of Python? Expand your data manipulation and analysis skills with the Python Libraries: NumPy, Matplotlib, and Pandas course. Dedicate 15 hours of learning to master concepts like vectors and dataframes, unlocking new possibilities in data science. Start your learning journey now!
Also Read: Top 16 Deep Learning Techniques to Know About in 2025
Now, let's shift our focus to another intriguing class of numbers: perfect squares, and explore how Python can be used to identify them.
While perfect numbers in Python relate to the sum of their divisors, perfect squares are defined by multiplication—an integer that’s the square of another (e.g., 9 = 3×3). Unlike perfect numbers, perfect squares involve a number whose square root is whole. Recognizing them is essential in both math and programming, presenting distinct challenges in Python.
Here’s how different numbers and their square roots help us determine perfect square status.
Number | Square Root | Perfect Square? |
4 |
2 |
Yes |
9 |
3 |
Yes |
10 |
3.16... |
No |
16 |
4 |
Yes |
25 |
5 |
Yes |
Now that we understand perfect squares, we can explore how to identify them using Python programmatically. Python offers several elegant and efficient ways to determine if a given number is a perfect square. Let's examine three distinct methods, each with its approach and computational characteristics.
Method 1: Using the Square Root
This method directly leverages the definition of a perfect square. We calculate the square root of the given number and then check if the result is an integer. If the square root is a whole number, then the original number is a perfect square. Furthermore:
Python Code:
import math
def is_perfect_square_sqrt(n):
if n < 0:
return False
root = math.isqrt(n) # Integer square root
return root * root == n
# Example
print(is_perfect_square_sqrt(49)) # True
print(is_perfect_square_sqrt(50)) # False
Output:
True
False
Explanation:
Method 2: Iterative Check
This method takes a more programmatic approach by iteratively checking if any integer, when squared, equals the given number. We can iterate through various integers and compare their squares with the input. While straightforward for understanding the concept, this approach has a time complexity of O(root n) in the worst case (as it iterates up to the square root). Therefore, this method is mainly educational and generally unsuitable for performance-sensitive applications dealing with large numbers.
Python Code:
def is_perfect_square(n):
if n < 0:
return False # Negative numbers can't be perfect squares
i = 0
while i * i <= n:
if i * i == n:
return True
i += 1
return False
# Test cases
test_numbers = [0, 1, 4, 9, 16, 14, 26, 100, -4, 121, 225, 300]
for num in test_numbers:
print(f"{num} is a perfect square: {is_perfect_square(num)}")
Output:
0 is a perfect square: True
1 is a perfect square: True
4 is a perfect square: True
9 is a perfect square: True
16 is a perfect square: True
14 is a perfect square: False
26 is a perfect square: False
100 is a perfect square: True
-4 is a perfect square: False
121 is a perfect square: True
225 is a perfect square: True
300 is a perfect square: False
Explanation:
Method 3: Binary Search
This method employs the efficient binary search algorithm to determine if a perfect square exists within a defined range. Since perfect squares increase monotonically, binary search can quickly narrow down the possibilities.
Python Code:
def is_perfect_square_binary_search(n):
if n < 0:
return False
left, right = 0, n
while left <= right:
mid = (left + right) // 2
square = mid * mid
if square == n:
return True
elif square < n:
left = mid + 1
else:
right = mid - 1
return False
# Example
print(is_perfect_square_binary_search(100)) # True
print(is_perfect_square_binary_search(101)) # False
Output:
True
False
Explanation:
Python provides several ways to check for perfect squares—from simple loops to math.isqrt() and binary search. math.isqrt() is ideal for quick, accurate checks. For deeper control or very large numbers, binary search offers the best performance. While Python handles large integers well, languages with fixed-size types require care to avoid overflow in methods like binary search. Choose your method based on performance needs, readability, and precisio.
Also Read: Everything You Need to Know About Binary Logistic Regression
Having explored the methods for identifying perfect squares, let's now focus on the fundamental difference between the two topics: perfect numbers and perfect squares.
Though both are mathematically 'perfect,' perfect numbers and perfect squares differ significantly in their fundamental structure, frequency, and the computational complexity involved in their identification. Understanding these distinctions is key to appreciating their unique places in number theory.
The key distinction between perfect numbers and perfect squares boils down to this:
To further illustrate the differences, consider the following table:
Feature | Perfect Squares | Perfect Numbers |
Definition | Integer multiplied by itself ((n = k^2)) | Sum of proper positive divisors equals the number |
Operation | Multiplication | Addition |
Derivation | Squaring an integer | Summing proper divisors |
Relationship | Number and its square root | Number and its proper divisors |
First Few | 1, 4, 9, 16, 25, 36, 49... | 6, 28, 496, 8128... |
How Common? | Infinitely many | Relatively rare; only a few are known |
In essence, while both terms involve a special property of integers, the nature of that property—multiplicative for perfect squares and additive for perfect numbers—sets them distinctly apart. Perfect squares are easily generated and verified, unlike the computationally expensive perfect number in Python. Understanding this difference is crucial when exploring various classifications and characteristics within number theory.
Also Read: Python Tutorial: Setting Up, Tools, Features, Applications, Benefits
Let's now consider the practical aspects of identifying perfect number in Python and perfect squares in Python. The following section will explore the computational considerations of finding these elusive numbers.
While exploring the definitions of perfect numbers and squares provides a foundational understanding, a deeper insight comes from examining the computational complexity of identifying perfect numbers versus the efficiency of verifying perfect squares.
Mathematical Relevance:
Both perfect number in Python and perfect squares hold intriguing positions within the realm of mathematics. Their unique properties have captured mathematicians for centuries.
Their study is fundamental to various areas of mathematics, including algebra, number theory, and geometry. They appear in solutions to quadratic equations, the Pythagorean theorem, and the geometric representation of squares. The distribution and properties of perfect squares have been extensively studied.
These elusive numbers have fascinated mathematicians since ancient times. Euclid mentioned them in his Elements, and their connection to Mersenne primes (primes of the form (2^p - 1)) through the Euclid-Euler theorem is a cornerstone result. This theorem states that every even perfect number can be expressed in the form (2^{p-1}(2^p - 1)), where (2^p - 1) is a Mersenne prime.
The existence of odd perfect numbers remains one of the oldest unsolved problems in number theory. Their rarity and specific structure make them objects of intense mathematical curiosity.
Also Read: Arithmetic Operators in Python: A Detailed Guide
Determining if a number is perfect typically involves finding and summing all its proper divisors. The efficiency of this process is crucial, especially when dealing with larger numbers.
Using generator functions or recursion (though with caution due to Python's recursion limit) can reduce memory usage, even if they don't always improve time complexity. For optimal time efficiency, the preferred method involves iterating
Checking whether a number is a perfect square can be much more efficient than checking for perfect numbers.
In summary, while both perfect numbers and perfect squares hold deep mathematical significance, the computational effort required to identify them differs drastically.
Perfect squares can be detected efficiently, whereas finding a perfect number in Python, especially larger ones, poses a significant computational challenge. This contributes to their rarity and the ongoing mathematical interest in their properties.
Also Read: Numpy Array in Python [Everything to know]
upGrad’s Exclusive Data Science Webinar for you –
Watch our Webinar on How to Build Digital & Data Mindset
Although rare and mostly theoretical, perfect number have some interesting applications in Python programming as well :
To identify perfect number in Python within a specific range, we can write a Python program that checks each number in the range to see if it is perfect. It's worth noting that only three perfect numbers exist between 1 and 1000, underscoring their rarity and providing a useful benchmark for verifying your code's correctness.
Python Code:
def is_perfect(n):
divisors = [i for i in range(1, n) if n % i == 0]
return sum(divisors) == n
perfect_numbers = [n for n in range(1, 1001) if is_perfect(n)]
print("Perfect numbers between 1 and 1000:", perfect_numbers)
Output:
Perfect numbers between 1 and 1000: [6, 28, 496]
Explanation:
This program defines a function is_perfect that checks if a number is perfect by summing its divisors and comparing the sum to the number itself. It then uses a list comprehension to find all perfect numbers in the range from 1 to 1000.
Implementing perfect number program in Python offers valuable opportunities to explore mathematical concepts, develop algorithmic skills, and lay the groundwork for more advanced topics in number theory and cryptography.
1. Educational Value:
2. Algorithmic Practice:
3. Foundation for Advanced Topics:
While perfect number programs provide educational insights, they come with limitations in computational efficiency and practical applicability.
1. Computational Complexity:
2. Limited Practical Use:
3. Open Problems:
Perfect number programs in Python offer valuable educational insights and algorithmic practice. They provide a fascinating glimpse into number theory and inspire further mathematical programming exploration. However, their computational inefficiency significantly limits their practical application. Consequently, they are excellent for learning but are rarely used in production systems.
Also Read: Top 15 Python Challenges for Beginners with Examples
So far, we have shown how understanding perfect numbers, while a specific mathematical concept, plays an integral part in demonstrating core programming principles like iteration, conditional logic, and algorithmic thinking. In Python, you can find perfect numbers by iterating through integers, identifying their divisors, and checking if their sum equals the original number.
upGrad empowers your Python journey beyond exploring concepts like perfect number program in Python to building a successful career. A leading online learning platform, upGrad boasts over 10 million learners, 200+ courses, and 1,400+ hiring partners.
In India, upGrad offers the following Python-related courses.
For those looking to get into advanced courses, upGrad offers a specialized Executive Post Graduate Certificate in AI and Data Science to fast-track your tech career as well.
Beyond these structured learning paths, you can also benefit from guidance from our expert advisors to choose the right path. For a more personal interaction, you can
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
763 articles published
Rohit Sharma shares insights, skill building advice, and practical tips tailored for professionals aiming to achieve their career goals.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources