Euler: Amicable numbers

Amicable numbers

This is the 21st issue of Euler Project Challenge Game.

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

Thinking:
1. To compute the sum of proper divisors as fast as possible. Refer to Problem 12.
2. Get each sums for every number from 1 to 10000, store these into a map or list.
3. Traverse again from 1 to 10000, accumulate the amicable numbers.


import math

def get_divisors_sum(num):
    sum = 1
    for i in range(2, (int)(math.sqrt(num))):
        if num%i == 0:
            sum += (i + num/i)
    return sum


def get_sum_from1ton(n):
    mlist = []
    mlist.append(0)
    for i in range(1, n):
        tmp = get_divisors_sum(i)
        mlist.append(tmp)
    return mlist


#print get_divisors_sum(220)
mlist = []
n = 10000
mlist = get_sum_from1ton(n)
#print mlist[284]
#print mlist[220]

total_sum = 0
for i in range(1, n):
    tmp = mlist[i]
    if tmp > n or tmp == i:
        continue
    if mlist[tmp] == i:
        total_sum += i
        print i
        print mlist[i]
        print mlist[mlist[i]]
        print 
        print

print total_sum
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章