Project Euler 21 Amicable numbers

Question

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.

Analysis

  1. 因子求和函数应该怎样优化?
  2. 字典来保存计算结果。
  3. 官方思路

Program

from math import sqrt, ceil


def get_sum(num):
    sum = 1
    mid = sqrt(num)
    for factor in range(2, ceil(mid) + 1):
        if num % factor == 0:
            sum += factor
            if factor != mid:
                sum += num // factor

    return sum


max_size = 10000
result = 0
cal = {}

for i in range(1, max_size):
    if cal.__contains__(i):
        a = cal[i]
    else:
        a = get_sum(i)
        cal[i] = a

    if cal.__contains__(a):
        b = cal[a]
    else:
        b = get_sum(a)
        cal[a] = b

    if i == b and i != a:
        result += i

print(result)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • 文/绘画:生凌君 我喜欢画花,各种花。普通的常见的花,如荷花之类的,也画过一些奇花异草,名不见经传的花。 也曾想改...
    生凌君君阅读 1,607评论 36 66
  • 小男孩出生时,你嘴里便一直说一个名字:小轩。那人们曾经的猜想没有错了。可能你生完孩子便被赶出来了。刚见到你时,你竟...
    帅气的昵称瑞阅读 203评论 0 0
  • 原文: 天长地久,天地所以能长且久者,以其不自生,故能长生。 是以圣人后其身而身先,外其身而身存。非以其无私邪?故...
    三炻阅读 298评论 0 1