我想打印所有素数,连续7个小于10000000000
。当使用range()
时,我得到一个MemoryError
,因为生成的数组无法存储,所以我将该循环更改为while
循环。用大数字进行Python优化
但是这个程序真的很慢。打印找到的第一个号码需要一分多钟。
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
i = 3
while i < math.sqrt(n) + 1:
#for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
i += 2
return True
def is_super_happy(n):
count = 0
while n != 0:
if n%10 == 7:
count += 1
if count == 7:
return True
else:
count = 0
n /= 10
return count == 7
i = 7777777
while i < 10e10:
#for i in range(7777777, int(10e10)):
if is_super_happy(i) and is_prime(i):
print i
i += 1
我不能想到任何事情都可以让这件事变得更快,我希望它变得非常快。
任何想法,提示?
你可以使用多利用其他CPU内核。 – 2014-11-04 15:06:23
不要使用'while',而是使用'xrange'而不是'range'(在Python 3中使用'range') – Unapiedra 2014-11-04 15:09:27
提示:你的数字都是十位数。其中7个是连续7次。有多少数字需要考虑? – RemcoGerlich 2014-11-04 15:15:47