Find count of Almost Prime numbers from 1 to N | Python 3 program to count almost prime numbers from 1 to n ; 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 ; Function to count almost prime numbers from 1 to n ; to store required answer ; 6 is first almost prime number ; to count prime factors ; if it is perfect square ; if I is almost prime number ; Driver Code
from math import * NEW_LINE N = 100005 NEW_LINE prime = [ True ] * N NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( N ) ) ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( 2 * p , N , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def almostPrimes ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 6 , n + 1 ) : NEW_LINE INDENT c = 0 NEW_LINE for j in range ( 2 , int ( sqrt ( i ) ) + 1 ) : NEW_LINE INDENT if i % j == 0 : NEW_LINE INDENT if j * j == i : NEW_LINE INDENT if prime [ j ] : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if prime [ j ] : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if prime [ i // j ] : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if c == 2 : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE n = 21 NEW_LINE print ( almostPrimes ( n ) ) NEW_LINE DEDENT