【发布时间】:2015-01-29 17:49:22
【问题描述】:
我的代码可以给出大多数素数,但它仍然包含 1 并遗漏了一些数字:23 和 47(在计算 100 以下的素数时)。出于某种原因,它包括 91,任何想法为什么? 我一直在使用Sieve of Atkin. 的维基百科说明
我的代码如下:
limit = 100
results = [2, 3, 5] #prime numbers
sieve = [i for i in range(limit + 1)] #numbers to test
TF = [False] * (limit + 1) #marks number as prime or not
ModFour = [1, 13, 17, 29, 37, 41, 49, 53]
ModSix = [7, 19, 31, 43]
ModTwelve = [11, 23, 47, 59]
for x in range(limit + 1):
for y in range(limit + 1):
test = 4 * x**2 + y**2
if test % 60 in ModFour:
try:
TF[test] = True
except IndexError:
pass
test = 3 * x**2 + y**2
if test % 60 in ModSix:
try:
TF[test] = True
except IndexError:
pass
if x > y:
test = 3 * x**2 - y**2
if test % 60 in ModTwelve:
try:
TF[test] = True
except IndexError:
pass
for n in range(2, limit + 1):
if TF[n] == True:
for x in range((n**2), (limit + 1), (n**2)):
TF[x] = False
for p in range(limit + 1):
if TF[p] == True:
results.append(sieve[p])
for prime in results:
print prime
欢迎对筛子的优化提出任何建议。 谢谢
【问题讨论】:
-
您是否将您的代码与this similar problem 进行了比较?检查你的逻辑在哪里偏离了他的。
-
@TheLaughingMan:当我这样做时,我的情况有所不同 - 如果在 ModFour(etc) 中测试 % 60 -。但是我不知道为什么他的作品,而我的作品却没有。他也在使用优化版本,因为他的范围是 limit + 1 的平方根。
标签: python python-2.7 primes sieve-of-atkin