Skip to content

Commit ab3769c

Browse files
committed
feat: add algorithm 95 to find the longest amicable chain
2 parents 7679c20 + a450acb commit ab3769c

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

project_euler/problem_095/sol1.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
chain.
1212
"""
1313

14+
1415
def sum_of_proper_divisors(n):
1516
"""Calculate the sum of proper divisors of n."""
1617
if n < 2:
@@ -27,11 +28,14 @@ def sum_of_proper_divisors(n):
2728

2829
return total
2930

31+
3032
def find_longest_amicable_chain(limit):
3133
"""Find the smallest member of the longest amicable chain under a given limit."""
3234
sum_divisors = {} # Dictionary to store the sum of proper divisors for each number
3335
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
3539

3640
longest_chain = [] # To store the longest amicable chain found
3741
seen = {} # Dictionary to track numbers already processed
@@ -46,7 +50,9 @@ def find_longest_amicable_chain(limit):
4650
while current <= limit and current not in chain:
4751
chain.append(current) # Add the current number to the chain
4852
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
5056

5157
# Check if we form a cycle and validate the chain
5258
if current in chain and current != start:
@@ -57,12 +63,16 @@ def find_longest_amicable_chain(limit):
5763
if len(chain) > len(longest_chain):
5864
longest_chain = chain # Update longest chain if this one is longer
5965

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+
6170

6271
def solution():
6372
"""Return the smallest member of the longest amicable chain under one million."""
6473
return find_longest_amicable_chain(10**6)
6574

75+
6676
if __name__ == "__main__":
6777
smallest_member = solution() # Call the solution function
6878
print(smallest_member) # Output the smallest member of the longest amicable chain

0 commit comments

Comments
 (0)