text: Sieve of Atkin | Python 3 program for implementation of Sieve of Atkin ; 2 and 3 are known to be prime ; Initialise the sieve array with False values ; Mark sieve [ n ] is True if one of the following is True : a ) n = ( 4 * x * x ) + ( y * y ) has odd number of solutions , i . e . , there exist odd number of distinct pairs ( x , y ) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b ) n = ( 3 * x * x ) + ( y * y ) has odd number of solutions and n % 12 = 7 c ) n = ( 3 * x * x ) - ( y * y ) has odd number of solutions , x > y and n % 12 = 11 ; Main part of Sieve of Atkin ; Mark all multiples of squares as non - prime ; Print primes using sieve [ ] ; Driver Code
code: def SieveOfAtkin ( limit ) : NEW_LINE INDENT if ( limit > 2 ) : NEW_LINE INDENT print ( 2 , end = " ▁ " ) NEW_LINE DEDENT if ( limit > 3 ) : NEW_LINE INDENT print ( 3 , end = " ▁ " ) NEW_LINE DEDENT sieve = [ False ] * limit NEW_LINE for i in range ( 0 , limit ) : NEW_LINE INDENT sieve [ i ] = False NEW_LINE DEDENT x = 1 NEW_LINE while ( x * x < limit ) : NEW_LINE INDENT y = 1 NEW_LINE while ( y * y < limit ) : NEW_LINE INDENT n = ( 4 * x * x ) + ( y * y ) NEW_LINE if ( n <= limit and ( n % 12 == 1 or n % 12 == 5 ) ) : NEW_LINE INDENT sieve [ n ] ^= True NEW_LINE DEDENT n = ( 3 * x * x ) + ( y * y ) NEW_LINE if ( n <= limit and n % 12 == 7 ) : NEW_LINE INDENT sieve [ n ] ^= True NEW_LINE DEDENT n = ( 3 * x * x ) - ( y * y ) NEW_LINE if ( x > y and n <= limit and n % 12 == 11 ) : NEW_LINE INDENT sieve [ n ] ^= True NEW_LINE DEDENT y += 1 NEW_LINE DEDENT x += 1 NEW_LINE DEDENT r = 5 NEW_LINE while ( r * r < limit ) : NEW_LINE INDENT if ( sieve [ r ] ) : NEW_LINE INDENT for i in range ( r * r , limit , r * r ) : NEW_LINE INDENT sieve [ i ] = False NEW_LINE DEDENT DEDENT DEDENT for a in range ( 5 , limit ) : NEW_LINE INDENT if ( sieve [ a ] ) : NEW_LINE INDENT print ( a , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT limit = 20 NEW_LINE SieveOfAtkin ( limit ) NEW_LINE