Amicable Pairs

Amicable Pairs with Python

Project to Learn Python

Amicable numbers, also known as an amicable pair, are two different numbers such that the sum of the proper divisors of each number is equal to the other number. In other words, if the sum of the proper divisors of one number equals the other number, and vice versa, then the two numbers are considered an amicable pair.

For example, the smallest pair of amicable numbers is (220, 284). The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110, and their sum is 284. The proper divisors of 284 are 1, 2, 4, 71, and 142, and their sum is 220.

The goal of this project to learn Python is to write a Python program to calculate and display amicable numbers under 20000.

Steps

  1. Create a function to calculate the sum of proper divisors of a given number.
  2. Iterate through the range of numbers from 2 to 20,000.
  3. For each number, calculate the sum of its proper divisors and check if it forms an amicable pair with another number.
  4. Print the pairs that satisfy the conditions of being amicable pairs.

Expected output

(220, 284)
(1184, 1210)
(2620, 2924)
(5020, 5564)
(6232, 6368)
(10744, 10856)
(12285, 14595)
(17296, 18416)

Solutions


def sum_of_proper_divisors(num):
    divisors_sum = 1
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            divisors_sum += i
            if i != num // i:
                divisors_sum += num // i
    return divisors_sum

def find_amicable_pairs(limit):
    amicable_pairs = []
    for num in range(2, limit):
        div_sum = sum_of_proper_divisors(num)
        if div_sum > num and sum_of_proper_divisors(div_sum) == num:
            amicable_pairs.append((num, div_sum))
    return amicable_pairs

# Calculate and display the amicable pairs below 20,000
pairs = find_amicable_pairs(20000)
for pair in pairs:
    print(pair)

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart