Euler Problem 95

The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.

Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair.

Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:

12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...)

Since this chain returns to its starting point, it is called an amicable chain.

Find the smallest member of the longest amicable chain with no element exceeding one million.


In [1]:
N = 10**6 + 1
divsum = [1] * N
divsum[0] = 0
divsum[1] = 0
longest_chain = 0
smallest_member = N

for d in range(2, N):
    for n in range(2*d, N, d):
        divsum[n] += d

seen = [False] * N
seen[0] = True
seen[1] = True
for n in range(2, N):
    if seen[n]:
        continue
    m = n
    orbit = []
    while m < N and not seen[m] and (m not in orbit):
        orbit.append(m)
        m = divsum[m]
    if m in orbit:
        k = orbit.index(m)
        cycle_len = len(orbit) - k
        if cycle_len > longest_chain:
            longest_chain = cycle_len
            smallest_member = min(orbit[k:])
        elif cycle_len == longest_chain:
            smallest_member = min(smallest_member, min(orbit[k:]))
    for m in orbit:
        seen[m] = True
print(smallest_member)


14316

In [ ]: