To efficiently find amicable numbers in Python, you can use the following approach:
- Define a function that calculates the sum of proper divisors for a given number.
- Iterate through a range of numbers and check if they form an amicable pair.
- Store the amicable pairs in a list.
- Return the list of amicable numbers.
Here's the Python code that implements these steps:
def sum_of_divisors(n):
# Calculates the sum of proper divisors for a given number 'n'
divisors_sum = 1
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
divisors_sum += i
if i != n // i:
divisors_sum += n // i
return divisors_sum
def find_amicable_numbers(limit):
amicable_numbers = []
for num in range(2, limit + 1):
sum_a = sum_of_divisors(num)
sum_b = sum_of_divisors(sum_a)
if num == sum_b and num != sum_a:
amicable_numbers.append((num, sum_a))
return amicable_numbers
limit = 10000 # Set the upper limit for the range of numbers to check
amicable_nums = find_amicable_numbers(limit)
print("Amicable numbers:")
for pair in amicable_nums:
print(pair)
limit = 10000 # Set the upper limit for the range of numbers to check amicable_nums = find_amicable_numbers(limit) print("Amicable numbers:") for pair in amicable_nums: print(pair)
In this code, the sum_of_divisors function calculates the sum of proper divisors for a given number n. The find_amicable_numbers function iterates over a range of numbers from 2 to the specified limit, checking if a number forms an amicable pair. If a pair is found, it is added to the amicable_numbers list. Finally, the list of amicable numbers is printed.
Feel free to adjust the limit variable to define the range of numbers you want to check for amicable pairs.