我试图解决this Project Euler question:优化非充裕资金算法
一个完美的编号是针对其适当的除数 的总和正好等于号。例如,28的适当 除数的和将是1 + 2 + 4 + 7 + 14 = 28,这意味着28 是一个完美的数字。
如果数字n的合适除数之和为 小于n,则该数字n称为不足,如果该和超过n,则称该数字为富余。
由于12是最小的丰富数字,1 + 2 + 3 + 4 + 6 = 16,可以写成两个丰富数字 之和的最小数字是24.通过数学分析,它可以是表明所有大于28123的整数 可以写成两个丰富数字的总和。 但是,即使已知不能被 表示为两个丰富数字之和的最大数量小于此限制,该上限也不能通过分析 进一步减少。
查找所有不能写为 的正整数的总和两个丰富数字的总和。
我的解决办法:
#returns a list of the divisors of a given number
def Divs(Number):
Divisors = []
for i in range(2 , int(Number**0.5) + 1):
if Number % i == 0:
Divisors.append(i)
for q in range(len(Divisors)):
if Divisors[q] != (Number/Divisors[q]):
Divisors.append(Number/Divisors[q])
Divisors.insert(0,1)
return Divisors
#returns a list of abundant numbers up to and including the limit
def AbList(limit):
Abundant = []
for i in range(11,limit + 1):
if sum(Divs(i)) > i:
Abundant.append(i)
return Abundant
#Finds the sum of all positive integers that cannot be written as the
#sum of two abundant numbers...
def AbSum(limit):
Abundant = AbList(limit)
NoAbSum = 0
for i in range(1 , limit):
AbSum = 0
x = 0
for x in Abundant:
if i - x in Abundant[:i]:
AbSum = 1
break
if AbSum == 0:
NoAbSum += i
return NoAbSum
这花了我3.4 GHz处理器,约15分钟就可以解决,我正在寻找一种更好的方式。我不关心前两个功能,因为他们一起运行时间不到一秒钟。第三个功能是踢球者。它贯穿数字的范围,达到极限(在这种情况下,是20000),每一次都会遍历丰富的数字列表,从当前数字中减去每个数字,然后在丰富的列表中检查该答案数字。如果有匹配,循环会中断并再次尝试下一个数字,一直到极限。
我知道这样做有更好的方式,但我在编程方面有点新。我如何加快这个算法?
你目前的解决方案是'O(m * n)`,其中`m`(极限)远远大于`n`(大于极限值的数量)。现在,计算所有数字*是其他丰富数字的总和的时间复杂度是多少?这比现在的解决方案好还是差? – 2011-02-03 03:41:15
你为什么要整理除数? – 2011-02-03 04:16:52
一旦您提交了正确的解决方案,您就可以访问该问题的讨论主题,您可以在其中找到一些最有效的解决方案。 – kefeizhou 2011-02-03 04:56:17