Back

Perfect Number in Python: A Comprehensive Guide

22 Jan 2024
4 min read

Python is an ideal language for exploring and solving mathematical and algorithmic problems due to its simplicity and flexibility. It allows for easy implementation of algorithms to identify perfect numbers, making it a popular choice for educational purposes and practical coding exercises. In this article, we will delve into the perfect number in Python, its significance, how to determine if a number is perfect using Python, and provide Python programs that can be used to identify perfect numbers, find perfect numbers between 1 to 1000, and even calculate perfect squares using loops.

What is a Perfect Number?

A perfect number is a positive integer equal to the sum of its proper divisors, excluding the number itself. In simpler terms, it's a number whose divisors (not including the number itself) add up to give the dividend.

In fact, every even perfect number is derived from a Mersenne prime using the Euclid-Euler theorem. According to this theorem, if 2ⁿ - 1 is a prime number (called a Mersenne prime), then the number 2ⁿ⁻¹ * (2ⁿ - 1) will be a perfect number

For example:

  • The divisors of 6 are 1, 2, and 3 which sum to 6
  • 1+2+3=6.
  • 28 is another example: 1+2+4+7+14=28.

Interesting facts about Perfect Number

  • All perfect numbers are even numbers. 
  • Perfect numbers end with 6 or 8 alternatively. 
  • The latest perfect number was discovered in 2018 and has 49,724,095 digits.

How to Write a Perfect Number Program in Python

A perfect number is a positive integer equal to the sum of its proper divisors, excluding the number itself. To check if a number is perfect, we need to follow these steps:

Steps to Check for a Perfect Number

Here are the steps to check the number is perfect number or not:

1. Identify the Proper Divisors: Proper divisors of a number nn are those integers that divide nn evenly, excluding nn itself.

For example, the proper divisors of 6 are 1, 2, and 3 because 6 ÷ 1 = 6, 6 ÷ 2 = 3, and 6 ÷ 3 = 2 (but we exclude 6).

2. Sum the Divisors: Once the proper divisors are found, sum them up. If the sum equals the original number, then it is a perfect number.

3. Logic Flow:

  • Loop through all numbers from 1 to n/2 to find divisors of n.
  • Sum the divisors.
  • Check if the sum equals n. If true, it's a perfect number.

Python Code

def is_perfect_number(n):
    # Initialize the sum of divisors
    divisors_sum = 0
    
    # Find divisors from 1 to n//2
    for i in range(1, n // 2 + 1):
        if n % i == 0:
            divisors_sum += i  # Add the divisor to the sum
    
    if divisors_sum == n:
        return True
    else:
        return False

# Test the function with an example
number = int(input("Enter a number: "))
if is_perfect_number(number):
    print(f"{number} is a perfect number.")
else:
    print(f"{number} is not a perfect number.")

Output

Enter number: 6
6 is perfect number 
 
Enter number: 28
28 is perfect number 

Enter number: 49
49 is prime number 

Explanation

  • The program asks for user input (a number to check if it's perfect).
  • The program loops through integers starting from 1 up to half of the number n. We only need to check up to n/2​ because no divisor of nn will be greater than n/2, except for n itself. For example, for n=28, divisors are 1, 2, 4, 7, and 14.
  • If n%i==0 (i.e., ii divides n with no remainder), the divisor is added to the sum.
  • Finally, if the sum of the divisors is equal to the original number, it is a perfect number. Otherwise, it is not.

Python Programs to Identify Perfect Numbers

This method uses a for loop to check each number from 1 to num-1 and sums the divisors. If the sum equals the number itself, it's considered a perfect number.

Method 1: Find Perfect Number in Python Using a For Loop

Positive integers are defined as perfect numbers, when their proper divisors are greater than the number itself, excluding the number itself. For example, 6 is a perfect number because the divisors of 6 are 1, 2, and 3, and 1 + 2 + 3 = 6.

Here's how to identify perfect numbers using a for loop in Python:

Python Code Example

def is_perfect_number(num):
    sum_of_divisors = 0
    for i in range(1, num):
        if num % i == 0:
            sum_of_divisors += i
    return sum_of_divisors == num

# Test
num = 28
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

Output

28 is a perfect number

Explanation

  • The function is_perfect_number checks if the sum of the divisors of the number 28 (excluding 28 itself) is equal to 2 is_perfect_number checks whether 28 is a perfect number if the sum of its divisors (excluding 28 itself) equals 28.
  • The divisors of 28 are 1, 2, 4, 7, and 14, and the sum of these divisors is 28.
  • Since the sum equals the number, the output is that 28 is a perfect number.

Method 2: Find Perfect Number in Python Using the While Loop

This method uses a while loop instead of a for loop to find the divisors of a number. In this case, we increment from 1 and continue until we reach half the number. It can be a good alternative when you prefer managing loop conditions explicitly.

Python Code Example

def is_perfect_number(num):
    sum_of_divisors = 0
    i = 1
    while i < num:
        if num % i == 0:
            sum_of_divisors += i
        i += 1
    return sum_of_divisors == num

# Test
num = 28
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

Code Explanation

The above code for perfect number in python defines a function is_perfect_number(num) that checks if a number is perfect by summing its proper divisors (excluding the number itself) and comparing the sum to the number. It tests the function with num = 28.

Output

28 is a perfect number.

Method 3: Find Perfect Number in Python Using Optimized Iteration (Factors up to num√2)

This method improves the efficiency by limiting the loop to only half of the number. This is because no divisor of a number can be greater than its half, except for the number itself.

Python Code Example

def is_perfect_number(num):
    sum_of_divisors = 0
    for i in range(1, num // 2 + 1):
        if num % i == 0:
            sum_of_divisors += i
    return sum_of_divisors == num

# Test
num = 28
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

Code Explanation

The above code for perfect number in Python defines a function is_perfect_number(num) that calculates the sum of proper divisors of num (from 1 to num // 2). It returns True if the sum equals the number, indicating it's perfect. The function is tested with num = 28, printing whether it's a perfect number.

Output

28 is a perfect number.

Method 4: Find Perfect Number in Python Using Recursion

Recursion involves a function calling itself with a simpler version of the problem until a base case is met. This method works well in functional programming paradigms.

Python Code Example

def sum_of_divisors(num, i=1, sum_of_divisors=0):
    if i >= num:
        return sum_of_divisors
    if num % i == 0:
        sum_of_divisors += i
    return sum_of_divisors(num, i + 1, sum_of_divisors)

def is_perfect_number(num):
    return sum_of_divisors(num) == num

# Test
num = 28
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

Code Explanation

The code for perfect number in Python defines a recursive function sum_of_divisors to calculate the sum of proper divisors of a number. The is_perfect_number function checks if this sum equals the number. It tests the function with num = 28 to determine if it's perfect.

Output

28 is a perfect number.

Method 5: Find Perfect Number in Python Using List Comprehension

List comprehension is a concise way to generate lists. It can also be used to compute the sum of divisors of a number in one line.

Python Code Example

def is_perfect_number(num):
    divisors = [i for i in range(1, num) if num % i == 0]
    return sum(divisors) == num

# Test
num = 28
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

Code Explanation

The code for perfect number in Python defines the function is_perfect_number(num), which finds all divisors of num (excluding num itself) and checks if their sum equals num. It tests the function with num = 28 to determine if it's a perfect number.

Output

28 is a perfect number.

Method 6: Find Perfect Number in Python Using Euclid-Euler Theorem

The Euclid-Euler theorem provides a way to identify perfect numbers based on prime numbers. It states that if 2^(p-1) * (2^p - 1) is a perfect number, where 2^p - 1 is a prime number (known as a Mersenne prime), then the product is a perfect number.

Python Code Example

def is_perfect_number(num):
    p = 2
    while True:
        mersenne_prime = (2 ** p) - 1
        if (2 ** (p - 1)) * mersenne_prime == num:
            return True
        if mersenne_prime > num:
            return False
        p += 1

# Test
num = 28
if is_perfect_number(num):
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")

Explanation

The above code for perfect number in python defines is_perfect_number(num) to check if a number is perfect by using Mersenne primes. It iterates through possible Mersenne primes 2p−1 and checks if the product 2p−1×(2p−1) equals num. It tests with num = 28.

Output

28 is a perfect number.

Perfect Numbers Between 1 to 1000 in Python

To find all perfect numbers between 1 and 1000, we can use any of the previously mentioned methods. Here, we will use the optimized iteration method, which runs a loop from 1 to num//2, because it is more efficient than checking divisors up to the number itself.

Code Example to Find Perfect Numbers Between 1 and 1000

def is_perfect_number(num):
 sum_of_divisors = 0
    for i in range(1, num // 2 + 1):
        if num % i == 0:
            sum_of_divisors += i
    return sum_of_divisors == num

def find_perfect_numbers_in_range(start, end):
    perfect_numbers = []
    for num in range(start, end + 1):
        if is_perfect_number(num):
            perfect_numbers.append(num)
    return perfect_numbers

# Find perfect numbers between 1 and 1000
perfect_numbers = find_perfect_numbers_in_range(1, 1000)
print("Perfect numbers between 1 and 1000:", perfect_numbers)

Output

Perfect numbers between 1 and 1000: [6, 28, 496]

Time Complexity Analysis of Perfect Number Algorithms

Time Complexity of Perfect Number Methods

Method Time Complexity Explanation
1. Using a For Loop O(n) Iterates through all numbers less than n to check divisibility, summing up the divisors and comparing to n.
2. Using a While Loop O(n) Similar to the for loop method but with a while loop structure. The complexity remains linear.
3. Optimized Iteration (Factors up to num/2) O(n) Reduces the number of iterations by checking divisors only up to n/2, but the overall time complexity is still linear.
4. Using Recursion O(n) The recursion process is equivalent to the for loop. Each recursive call adds one divisor, making the time complexity linear.
5. Using List Comprehension O(n) Uses Python's list comprehension to find divisors and sum them. Although compact, the complexity remains O(n) because it iterates over all numbers less than n.
6. Using Euclid-Euler Theorem O(1) Based on the Euclid-Euler theorem, this method generates even perfect numbers directly using Mersenne primes, making it constant time O(1).

Perfect Square Program in Python

A perfect square program in Python checks if a given number is a perfect square. A perfect square is a positive integer that is the product of two equal integers.

Perfect Square Program in Python Using For Loop

A perfect square is a number that can be written as the square of an integer (e.g., 16 = 4²). This is different from a perfect number, which is a number equal to the sum of its divisors (excluding itself).

Difference Between Perfect Numbers and Perfect Squares:

  • Perfect Numbers are numbers equal to the sum of their divisors excluding themselves.
  • Perfect Squares are numbers that are squares of integers (e.g., x2).

Code

import math

def is_perfect_square(num):
    root = math.isqrt(num)
    return num == root * root

# Test
num = 16
if is_perfect_square(num):
    print(f"{num} is a perfect square.")
else:
    print(f"{num} is not a perfect square.")

Output

16 is perfect square.

Explanation

The program checks if a number is a perfect square by calculating its integer square root using math.isqrt() and verifying if squaring the root equals the original number.

Perfect Numbers vs Perfect Squares

Here are the key differences between perfect numbers and perfect squares:

Perfect Numbers vs. Perfect Squares

Perfect Numbers Perfect Squares
A number equal to the sum of its proper divisors (excluding the number itself). A number that is the square of an integer.
The perfect numbers are 6, 28, 496, 8128, 33550336 The perfect squares are 1, 4, 9, 16, 25, 36, 49, 64, 81
It is represented by σ(n)=2n where σ(n) is the sum of divisors function It is represented by n² where n is an integer
All known perfect numbers are even, but it's not proven that no odd perfect numbers exist Can be both even or odd, depending on the integer being squared
It is used very rarely such as in some number theory problems It is used very common often seen in geometry, algebra, and real-world scenarios

Applications of Perfect Numbers

Here are the applications of perfect numbers in python:

1. Mathematics

  • Number Theory: Perfect numbers are linked to Mersenne primes and Euclid-Euler’s theorem, aiding the study of divisors, primes, and algebraic structures.
  • Prime Research: Perfect numbers help in the search for new primes, particularly Mersenne primes.

2. Cryptography

Prime Numbers: While not directly used, perfect numbers' relationship with prime numbers supports encryption methods like RSA and elliptic curve cryptography (ECC).

3. Programming

  • Algorithm Design: Perfect numbers teach efficient algorithms, especially for divisor checking and optimization.
  • Mathematical Software: Used in tools for number theory, primality testing, and puzzles.

Conclusion

In conclusion, perfect numbers in Python can be identified using a variety of methods, ranging from simple for loops to more optimized techniques. Each approach not only demonstrates efficient coding practices but also serves as an excellent exercise for developing algorithmic thinking and a deeper understanding of the mathematical concepts behind perfect numbers. Whether for educational purposes, mathematical research, or practical implementation in programming, these methods provide a solid foundation for working with perfect numbers.

Frequently Asked Questions

1. What is the perfect number code in Python? 

The perfect number code in Python typically involves a loop or recursion to find the divisors of a number and then check if their sum equals the number. If they match, the number is perfect.

2. What is a perfect number in Python? 

A perfect number in Python is a number that is equal to the sum of its proper divisors, excluding itself. For example, 6 is a perfect number because the sum of its divisors (1, 2, and 3) equals 6.

3. How to write a perfect number program in Python? 

A program to identify a perfect number in Python can be written by iterating through the divisors of a number, summing them up, and comparing the sum to the original number. If the sum equals the number, it is considered perfect.

4. What is the Python perfect number program? 

A Python perfect number program identifies whether a given number is perfect by checking if the sum of its divisors (excluding itself) is equal to the number.

5. How can I use a perfect number program in real-world applications?

A: While perfect numbers themselves may not be widely used in practical applications, the algorithms for identifying them are often used in coding challenges and programming practice to help you learn efficient looping, recursion, and algorithmic optimization.

Read More Articles

Chat with us
Chat with us
Talk to career expert