【问题标题】:Project Euler 23: Why is my code so slow and what can I do to speed it up?Project Euler 23:为什么我的代码这么慢,我该怎么做才能加快速度?
【发布时间】:2014-11-16 16:18:39
【问题描述】:

这里是问题的链接:link。我的代码似乎呈指数级下降,但我无法确定原因或更有效的算法。我的方法是通过从原始数字中减去每个数字并查看差异是否在丰富数字列表内来识别直到上限的所有丰富数字,并识别出不是数字总和的上限的数字。关于正在发生的事情和/或解决此问题的更好方法的任何想法?

这是我使用的代码:

import numpy as np 
import math
import itertools

def divisors(n): return sorted(np.unique(np.array([[x,n/x] for x in range(1,int(round(math.sqrt(n))+1)) if n%x == 0]).flatten()).tolist())[0:-1]



ubound = 28123
abundant_numbers = [x for x in range(1,ubound) if x < sum(divisors(x))] 


def is_sum_of_abundant(n):
    isob = False
    for i in abundant_numbers:
        if (n - i) <=0: 
            continue
        else:
            if (n - i) in abundant_numbers:
                isob = True 
    return isob

s = 0

for x in range(1,ubound):
    print "%.2f percent\n" % ((float(x)/ubound)*100)
    if is_sum_of_abundant(x):
        print "{} is abundant".format(x)
    else:
        s+=x
        print "{} is not abundant".format(x)
print s

【问题讨论】:

    标签: python performance algorithm


    【解决方案1】:

    您尝试的一件事是计算除数之和的更好方法 - 请参阅 sigma 函数 here 的定义。从本质上讲,您会找到主要因素并使用以下事实:

    sigma(ab) = sigma(a) * sigma(b)
    sigma(p^n) = (p^(n+1)-1)/(p-1)
    

    其中 sigma(n) 是正除数的总和。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 2013-01-18
      • 2012-08-19
      相关资源
      最近更新 更多