如何改进项目Euler 580解决方案

时间:2017-02-06 18:23:48

标签: python

这是问题文本:

  

希尔伯特数是整数k≥0k≥0时形式为4k + 14k + 1的任何正整数。我们将一个无平方的希尔伯特数定义为希尔伯特数,该数不能被除了一个以外的任何希尔伯特数的平方整除。例如,117117是平方自由希尔伯特数,等于9×139×13。然而62376237是希尔伯特数,在这个意义上不是无平方,因为它可以被9292整除。数字39693969也不是无平方,因为它可以被9292和212212整除。

     

有23271922327192平方自由希尔伯特数低于107107。   在10161016以下有多少平方免费希尔伯特数?

以下是我的代码。我怎样才能让它更快?

from math import sqrt

def if_squarefree(x):

i = 1
maybe = 0

while maybe < int(sqrt(x)) + 1 :

    tmp = 4 * i + 1

    maybe = tmp * tmp

    if x % maybe == 0 :
        return False
    i = i + 1

return True

def find_squarefree() :

end = pow(10,16)
i = pow(10,7)
cnt = 0

while i < end :
    print i
    tmp = 4 * i + 1
    if if_squarefree(tmp) :
        cnt = cnt + 1
    i = i + 1
return cnt


find_squarefree()
谢谢你:)

1 个答案:

答案 0 :(得分:0)

我认为你错了。尝试运行此程序:

from __future__ import absolute_import, division, print_function

from datetime import datetime

start = datetime.utcnow()
i = 0

while True:
    i += 1
    if i % 10**7 == 0:
        print(i)
        print((datetime.utcnow() - start ).total_seconds())

请注意计算10**7又名pow(10,7)需要多长时间。现在想象一下如何计算pow(10,16)。 这只是while i < end循环中的计数 - 这是在if_squrefree()

调用中排除循环

在我的盒子上。从1开始计数 - > 1000000需要1.4秒。通过数学 从1开始计数 - > 100亿将需要〜45年。因此,这种方法不起作用。

相关问题