简体   繁体   English

为什么我的Eratosthenes筛网会除去非素数?

[英]Why is my Sieve of Eratosthenes removing the non-prime numbers?

My code: 我的代码:

def sieve(list1):

    not_prime = set()
    primes = []
    for i in range(2, list1+1):
        if i in not_prime:
            continue
        for x in range(i*2, list1+1, i):
            not_prime.add(x)
        primes.append(i)
    return primes

I am trying to keep the non-prime numebrs and change it to 0. Where am I going wrong? 我试图保留非素数并将其更改为0。我在哪里出错? The output doesn't even show any other number besides the prime numbers. 除质数外,输出甚至不显示任何其他数字。

Well in that case, cant you just append zero instead of continue in the no_prime clause? 那么,在这种情况下,您不能只添加零而不是在no_prime子句中继续吗?

def sieve(list1):
    not_prime = set()
    primes = []
    for i in range(2, list1+1):
        if i in not_prime:
            primes.append(0);
            continue;
        for x in range(i*2, list1+1, i):
            not_prime.add(x)
        primes.append(i)
    return primes



sieve(27)

# output [2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0]

Or if this is anything beyond a toy, you probably want to look into sparse arrays. 或者,如果这不是玩具之外的任何东西,您可能想研究稀疏数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM