亲和数(Amicable Numbers)是指两个不同的正整数,它们的真因数(即除去本身的所有因数)之和与对方的数相等。
def sum_of_proper_divisors(n):
"""计算一个数的真因子之和"""
divisors_sum = 1 # 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_pairs(limit):
"""查找所有两个整数都小于给定上限的亲和对"""
amicable_pairs = []
for num in range(2, limit):
partner = sum_of_proper_divisors(num)
if partner > num and partner < limit and sum_of_proper_divisors(partner) == num:
amicable_pairs.append((num, partner))
return amicable_pairs
if __name__ == "__main__":
limit = 10000
amicable_pairs = find_amicable_pairs(limit)
print(f"All amicable pairs below {limit}:")
for pair in amicable_pairs:
print(pair)
All amicable pairs below 10000:
(220, 284)
(1184, 1210)
(2620, 2924)
(5020, 5564)
(6232, 6368)