Sieve of Eratosthenes - Finding Primes Python

前端 未结 17 2324
旧巷少年郎
旧巷少年郎 2020-11-22 04:40

Just to clarify, this is not a homework problem :)

I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.

17条回答
  •  旧时难觅i
    2020-11-22 05:06

    I just came up with this. It may not be the fastest, but I'm not using anything other than straight additions and comparisons. Of course, what stops you here is the recursion limit.

    def nondivsby2():
        j = 1
        while True:
            j += 2
            yield j
    
    def nondivsbyk(k, nondivs):
        j = 0
        for i in nondivs:
            while j < i:
                j += k
            if j > i:
                yield i
    
    def primes():
        nd = nondivsby2()
        while True:
            p = next(nd)
            nd = nondivsbyk(p, nd)
            yield p
    
    def main():
        for p in primes():
            print(p)
    

提交回复
热议问题