Almost Prime Numbers | A function to count all prime factors of a given number ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , count i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; A function to print the first n numbers that are k - almost primes . ; Print this number if it is k - prime ; Increment count of k - primes printed so far ; Driver Code
function countPrimeFactors ( n ) { let count = 0 ; while ( n % 2 == 0 ) { n = n / 2 ; count ++ ; } for ( let i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { n = n / i ; count ++ ; } } if ( n > 2 ) count ++ ; return ( count ) ; } function printKAlmostPrimes ( k , n ) { for ( let i = 1 , num = 2 ; i <= n ; num ++ ) { if ( countPrimeFactors ( num ) == k ) { document . write ( num + " " ) ; i ++ ; } } return ; } let n = 10 , k = 2 ; document . write ( " " + n + " " + k + " " + " " ) ; printKAlmostPrimes ( k , n ) ;