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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值