Find count of Almost Prime numbers from 1 to N | Javascript 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
let N = 100005 ; let prime = new Array ( N ) . fill ( true ) ; function SieveOfEratosthenes ( ) { prime [ 1 ] = false ; for ( let p = 2 ; p < Math . floor ( Math . sqrt ( N ) ) ; p ++ ) { if ( prime [ p ] == true ) for ( let i = 2 * p ; i < N ; i += p ) prime [ i ] = false ; } } function almostPrimes ( n ) { let ans = 0 ; for ( let i = 6 ; i < n + 1 ; i ++ ) { let c = 0 ; for ( let j = 2 ; i >= j * j ; j ++ ) { if ( i % j == 0 ) { if ( j * j == i ) { if ( prime [ j ] ) c += 1 ; } else { if ( prime [ j ] ) c += 1 ; if ( prime [ ( i / j ) ] ) c += 1 ; } } } if ( c == 2 ) ans += 1 ; } return ans ; } SieveOfEratosthenes ( ) ; let n = 21 ; document . write ( almostPrimes ( n ) ) ;