11
11
chain.
12
12
"""
13
13
14
+
14
15
def sum_of_proper_divisors (n ):
15
16
"""Calculate the sum of proper divisors of n."""
16
17
if n < 2 :
@@ -27,11 +28,14 @@ def sum_of_proper_divisors(n):
27
28
28
29
return total
29
30
31
+
30
32
def find_longest_amicable_chain (limit ):
31
33
"""Find the smallest member of the longest amicable chain under a given limit."""
32
34
sum_divisors = {} # Dictionary to store the sum of proper divisors for each number
33
35
for i in range (1 , limit + 1 ):
34
- sum_divisors [i ] = sum_of_proper_divisors (i ) # Calculate and store sum of proper divisors
36
+ sum_divisors [i ] = sum_of_proper_divisors (
37
+ i
38
+ ) # Calculate and store sum of proper divisors
35
39
36
40
longest_chain = [] # To store the longest amicable chain found
37
41
seen = {} # Dictionary to track numbers already processed
@@ -46,7 +50,9 @@ def find_longest_amicable_chain(limit):
46
50
while current <= limit and current not in chain :
47
51
chain .append (current ) # Add the current number to the chain
48
52
seen [current ] = True # Mark this number as seen
49
- current = sum_divisors .get (current , 0 ) # Move to the next number in the chain
53
+ current = sum_divisors .get (
54
+ current , 0
55
+ ) # Move to the next number in the chain
50
56
51
57
# Check if we form a cycle and validate the chain
52
58
if current in chain and current != start :
@@ -57,12 +63,16 @@ def find_longest_amicable_chain(limit):
57
63
if len (chain ) > len (longest_chain ):
58
64
longest_chain = chain # Update longest chain if this one is longer
59
65
60
- return min (longest_chain ) if longest_chain else None # Return the smallest member of the longest chain
66
+ return (
67
+ min (longest_chain ) if longest_chain else None
68
+ ) # Return the smallest member of the longest chain
69
+
61
70
62
71
def solution ():
63
72
"""Return the smallest member of the longest amicable chain under one million."""
64
73
return find_longest_amicable_chain (10 ** 6 )
65
74
75
+
66
76
if __name__ == "__main__" :
67
77
smallest_member = solution () # Call the solution function
68
78
print (smallest_member ) # Output the smallest member of the longest amicable chain
0 commit comments