Part of the series

Several example codes

~2 min read • Updated Oct 13, 2025

Program Overview

This Python program reads an integer n and displays all amicable number pairs from 1 to n.
It uses a helper function to compute the sum of proper divisors.


Python Code:


def sum_of_divisors(num: int) -> int:
    total = 0
    for i in range(1, num):
        if num % i == 0:
            total += i
    return total

def find_amicable_pairs(limit: int):
    seen = set()
    for a in range(2, limit + 1):
        if a in seen:
            continue
        b = sum_of_divisors(a)
        if b != a and sum_of_divisors(b) == a:
            print(f"{a} and {b} are amicable numbers")
            seen.add(a)
            seen.add(b)

# Read input from user
n = int(input("Enter value for n: "))
find_amicable_pairs(n)

Sample Output (input: n = 300):


220 and 284 are amicable numbers

Written & researched by Dr. Shahin Siami