To solve this problem (assuming it refers to Project Euler Problem 21: Amicable Numbers), we need to find the sum of all amicable numbers under 10000. Amicable numbers are pairs where each number is the sum of the proper divrs of the other.
Approach
- Sum of Proper Divrs: For each number
n, compute the sum of its proper divrs (divrs excludingnitself). This can be done efficiently by iterating up to the square root ofnand adding both divrs if they are distinct. - Identify Amicable Pairs: For each number
afrom 2 to 9999:- Compute
bas the sum of proper divrs ofa. - Check if
b > a(to avoid duplicate pairs) and if the sum of proper divrs ofbequalsa. - If both conditions are met, add both
aandbto the total sum.
- Compute
Solution Code
def sum_proper_divrs(n):
if n == 1:
return 0
total = 1 # 1 is a proper divr for all n > 1
sqrt_n = int(n ** 0.5)
for i in range(2, sqrt_n + 1):
if n % i == 0:
total += i
other = n // i
if other != i:
total += other
return total
sum_amicable = 0
seen = set()
for a in range(2, 10000):
if a in seen:
continue
b = sum_proper_divrs(a)
if b > a and b < 10000 and sum_proper_divrs(b) == a:
sum_amicable += a + b
seen.add(a)
seen.add(b)
print(sum_amicable)
Explanation
- Sum of Proper Divrs: The function
sum_proper_divrscalculates the sum of divrs by checking up to the square root ofn, ensuring efficiency (O(√n) per number). - Amicable Pairs: By checking
b > a, we avoid processing the same pair twice (e.g., 220 and 284 are only considered once whena=220). Theseenset ensures we don't add duplicate numbers to the sum.
Answer: 31626. This is the sum of all amicable numbers under 10000.
\boxed{31626}


作者声明:本文包含人工智能生成内容。