Sieve Of Atkin Implementation in Python

后端 未结 2 1300
無奈伤痛
無奈伤痛 2020-12-11 05:12

I am trying to implement the algorithm of Sieve of Atkin given in Wikipedia Link as below:

Sieve Of Atkin

What I\'ve tried so far is the implementation in Py

2条回答
  •  Happy的楠姐
    2020-12-11 05:21

    Here is a solution

    import math
    
    def sieveOfAtkin(limit):
        P = [2,3]
        sieve=[False]*(limit+1)
        for x in range(1,int(math.sqrt(limit))+1):
            for y in range(1,int(math.sqrt(limit))+1):
                n = 4*x**2 + y**2
                if n<=limit and (n%12==1 or n%12==5) : sieve[n] = not sieve[n]
                n = 3*x**2+y**2
                if n<= limit and n%12==7 : sieve[n] = not sieve[n]
                n = 3*x**2 - y**2
                if x>y and n<=limit and n%12==11 : sieve[n] = not sieve[n]
        for x in range(5,int(math.sqrt(limit))):
            if sieve[x]:
                for y in range(x**2,limit+1,x**2):
                    sieve[y] = False
        for p in range(5,limit):
            if sieve[p] : P.append(p)
        return P
    
    print sieveOfAtkin(100)
    

提交回复
热议问题