How to find perfect number in Python

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 the int function. We then pass this integer to the is_perfect Python function and print out whether the number is perfect or not.

Output:

How to find perfect number in Python

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 number n 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 number n. It initializes an empty list perfect_numbers to store the perfect numbers. Then it enters a Python for loop that iterates over each number i from 1 up to n. If i is a perfect number (as determined by the is_perfect function), it gets appended to perfect_numbers. After the for loop has finished running, the function returns the perfect_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 using Function in Python

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 number n 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 to n to see if it’s a divisor. sum: The current sum of n‘s divisors.
  • If n is divisible by x, x is added to sum. When x equals n, the function checks if sum equals n, indicating that n 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 the is_perfect function, then prints whether the number is a perfect number based on the function’s return value.

Output:

Perfect Number in Python using Recursion

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}.")

  1. is_perfect(n, x=1, sum=0): This Python function checks whether a given number n is perfect, using a recursive approach. A perfect number is equal to the sum of its divisors (excluding the number itself).
  2. find_perfect_numbers_in_range(start, end): This is another Python recursive function which finds all the perfect numbers in a given range, from start to end.
    • If start is greater than end, 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. If start is a perfect number, as determined by the is_perfect function, it’s added to the front of the list of perfect numbers rest. If start isn’t a perfect number, it just returns rest.
  3. 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 the perfect_numbers list.

Output:

Perfect Number in Python

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.