Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Euler23项目:为什么我的代码这么慢,我能做些什么来加速它?_Python_Performance_Algorithm - Fatal编程技术网

Python Euler23项目:为什么我的代码这么慢,我能做些什么来加速它?

Python Euler23项目:为什么我的代码这么慢,我能做些什么来加速它?,python,performance,algorithm,Python,Performance,Algorithm,以下是指向问题的链接:。我的代码速度似乎呈指数级下降,但我无法确定原因或更有效的算法。我的方法是通过从原始数字中减去每个数字,并查看差异是否在丰富数字列表中,来确定所有达到极限的丰富数字,并确定达到上限的数字不是这些数字的总和。关于目前的情况和/或解决这个问题的更好方法,有什么想法吗 以下是我使用的代码: import numpy as np import math import itertools def divisors(n): return sorted(np.unique(np.ar

以下是指向问题的链接:。我的代码速度似乎呈指数级下降,但我无法确定原因或更有效的算法。我的方法是通过从原始数字中减去每个数字,并查看差异是否在丰富数字列表中,来确定所有达到极限的丰富数字,并确定达到上限的数字不是这些数字的总和。关于目前的情况和/或解决这个问题的更好方法,有什么想法吗

以下是我使用的代码:

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
将numpy导入为np
输入数学
进口itertools
def除数(n):返回排序(np.unique(np.array([[x,n/x]表示范围内的x(1,int(round(math.sqrt(n))+1)),如果n%x==0])。flatte()).tolist())[0:-1]
ubound=28123
丰富的_数=[x表示范围(1,ubound)内的x,如果x如果(n-i)你尝试的一件事是计算除数之和的更好的方法-参见西格玛函数的定义。基本上,你可以找到主要因素,并利用以下事实

sigma(ab) = sigma(a) * sigma(b)
sigma(p^n) = (p^(n+1)-1)/(p-1)
其中sigma(n)是正因子之和