In this Python Tutorial, we will learn how to find the perfect number in Python. In addition, we will learn the finding of perfect numbers using function and recursion with examples. Moreover, we will cover finding the perfect number individually and also within the range.
Perfect Number in Python
Before we dive into the programming side of things, it’s important to first understand what a perfect number is.
In mathematics, a perfect number is a positive integer that is equal to the sum of its positive divisors excluding the number itself. For instance, the first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Other examples of perfect numbers are 28, 496, and 8128.
Perfect Number using Function in Python
Let’s explore how we can implement a function in Python to check if a number is perfect. There are two scenarios where we check either for the individual number or for a range of numbers.
Perfect Number for Single Number in Python
Python is a great language for this task due to its readability and simplicity. Here’s a basic function that checks if a given number is perfect:
def is_perfect(n):
sum = 1 # start with 1 because it's a divisor of every number
i = 2
while i * i <= n:
if n % i:
i += 1
else:
if i * (n // i) == n:
sum = sum + i + n//i
i += 1
return sum == n and n!=1
# Take input from user
number = int(input("Enter a number to check if it's perfect: "))
# Use the function and print the result
if is_perfect(number):
print(f"The number {number} is a perfect number.")
else:
print(f"The number {number} is not a perfect number.")
- In this Python function, we iterate from 2 to sqrt(n). For every number we find that divides evenly into n, we add it to the sum. If the number is its own pair (i.e., if n is a perfect square), we only add it once. In the end, if the sum is equal to n, and n is not 1, we return True (because the number is perfect). Otherwise, we return False.
- We use the Python
input
function to take a number from the user, then convert that input into an integer with theint
function. We then pass this integer to theis_perfect
Python function and print out whether the number is perfect or not.
Output:
Checking Perfect Numbers in a Range in Python
We can also create a Python function to find all the perfect numbers in a range. This is useful if we want to find all perfect numbers between 1 and 10000, for instance:
def is_perfect(n):
sum = 1 # start with 1 because it's a divisor of every number
i = 2
while i * i <= n:
if n % i:
i += 1
else:
if i * (n // i) == n:
sum = sum + i + n//i
i += 1
return sum == n and n!=1
def find_perfect_numbers(n):
perfect_numbers = []
for i in range(1, n+1):
if is_perfect(i):
perfect_numbers.append(i)
return perfect_numbers
# Take input from user
end = int(input("Enter a number to find all perfect numbers up to: "))
# Use the function and print the result
perfect_numbers = find_perfect_numbers(end)
if perfect_numbers:
print(f"The perfect numbers up to {end} are: {perfect_numbers}")
else:
print(f"There are no perfect numbers up to {end}.")
This code consists of two main parts: the function definitions and the user interaction.
Function Definitions:
The code defines two functions: is_perfect
and find_perfect_numbers
.
is_perfect(n)
: This Python function checks if a numbern
is perfect – meaning that it’s equal to the sum of its divisors excluding the number itself.find_perfect_numbers(n)
: This Python function finds all perfect numbers up to a given numbern
. It initializes an empty listperfect_numbers
to store the perfect numbers. Then it enters a Python for loop that iterates over each numberi
from 1 up ton
. Ifi
is a perfect number (as determined by theis_perfect
function), it gets appended toperfect_numbers
. After the for loop has finished running, the function returns theperfect_numbers
list.
User Interaction:
The script asks the user to input a number and finds all perfect numbers up to this number using Python find_perfect_numbers
. It then prints the perfect numbers, or a message indicating that there are no perfect numbers up to the input number if the list of perfect numbers is empty.
Output:
Perfect Number in Python using Recursion
Now, let’s explore how we can create a recursive function to check for perfect numbers in Python.
def is_perfect(n, x=1, sum=0):
if x >= n:
return sum == n
else:
if n % x == 0:
sum += x
return is_perfect(n, x + 1, sum)
# Take input from user
number = int(input("Enter a number to check if it's perfect: "))
# Use the function and print the result
if is_perfect(number):
print(f"The number {number} is a perfect number.")
else:
print(f"The number {number} is not a perfect number.")
Here, is the explanation:
is_perfect(n, x=1, sum=0)
: This Python function is a recursive implementation that checks if a given numbern
is a perfect number. A perfect number is one whose divisors, excluding the number itself, sum up to the number. The function has three parameters:n
: The number to check.x
: A counter that starts from 1 and checks every number up ton
to see if it’s a divisor.sum
: The current sum ofn
‘s divisors.
- If
n
is divisible byx
,x
is added tosum
. Whenx
equalsn
, the function checks ifsum
equalsn
, indicating thatn
is a perfect number. - Then, the Python script asks the user to enter a number using Python’s
input
function. It passes the entered number to theis_perfect
function, then prints whether the number is a perfect number based on the function’s return value.
Output:
Python Recursive Function to Find Perfect Numbers in a Range
We can extend our function to find all perfect numbers within a given range. Here’s how we can do that:
def is_perfect(n, x=1, sum=0):
if x >= n:
return sum == n
else:
if n % x == 0:
sum += x
return is_perfect(n, x + 1, sum)
def find_perfect_numbers_in_range(start, end):
if start > end:
return []
else:
rest = find_perfect_numbers_in_range(start+1, end)
if is_perfect(start):
return [start] + rest
else:
return rest
# Taking user input for the start and end of the range
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
# Finding and printing the perfect numbers in the range
perfect_numbers = find_perfect_numbers_in_range(start, end)
if perfect_numbers:
print(f"The perfect numbers in the range {start} to {end} are: {perfect_numbers}")
else:
print(f"There are no perfect numbers in the range {start} to {end}.")
is_perfect(n, x=1, sum=0)
: This Python function checks whether a given numbern
is perfect, using a recursive approach. A perfect number is equal to the sum of its divisors (excluding the number itself).find_perfect_numbers_in_range(start, end)
: This is another Python recursive function which finds all the perfect numbers in a given range, fromstart
toend
.- If
start
is greater thanend
, the function returns an empty list as there are no numbers to check. - Otherwise, it makes a recursive call to itself, incrementing
start
by one to get the rest of the perfect numbers in the range. Ifstart
is a perfect number, as determined by theis_perfect
function, it’s added to the front of the list of perfect numbersrest
. Ifstart
isn’t a perfect number, it just returnsrest
.
- If
- The Python script asks the user to input the start and end of the range. It then calls
find_perfect_numbers_in_range
with these values to find the perfect numbers within that range. The found perfect numbers are stored in theperfect_numbers
list.
Output:
Conclusion
Python provides a simple and intuitive way to solve mathematical problems like finding perfect numbers. This exercise not only helps improve programming skills but also helps appreciate the beauty of mathematics.
In this article, we have explored the concept of perfect numbers and how to find them using a recursive function and a simple function in Python.
You may also like to read the following Python tutorials.
- Remove Unicode characters in python
- NameError: name is not defined in Python
- Check if a number is a prime Python
- Python built-in functions with examples
- Python Program to Check Prime Numbers [6 methods]
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.