【问题标题】:Python Implementation of the Sieve of Atkin阿特金筛子的 Python 实现
【发布时间】: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


【解决方案1】:

您没有翻转TF[test] - 您只是将这些元素设置为True。对比(this SO question)处的代码:

test = 4 * x**2 + y**2    | n = 4*x**2 + y**2
if test % 60 in ModFour:  | if n<=limit and (n%12==1 or n%12==5):
  try:                    |  
    TF[test] = True       |   is_prime[n] = not is_prime[n]
  except IndexError:      | 
    pass                  |

要从results 中删除1,只需在构建results 列表时从TF[5] 开始:

for p in range(5, limit + 1):
    if TF[p] == True:
        results.append(sieve[p])

【讨论】:

  • 谢谢,现在可以了。你能解释一下为什么我的代码最初不能正常工作吗?
猜你喜欢
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多