Sieve of Eratosthenes | Python program to print all primes smaller than or equal to n using Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers ; Driver code
def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT print p , NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 30 NEW_LINE print " Following ▁ are ▁ the ▁ prime ▁ numbers ▁ smaller " , NEW_LINE print " than ▁ or ▁ equal ▁ to " , n NEW_LINE SieveOfEratosthenes ( n ) NEW_LINE DEDENT