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
< ? php function countPrimeFactors ( $ n ) { $ count = 0 ; while ( $ n % 2 == 0 ) { $ n = $ n / 2 ; $ count ++ ; } for ( $ i = 3 ; $ i <= sqrt ( $ n ) ; $ i = $ i + 2 ) { while ( $ n % $ i == 0 ) { $ n = $ n / $ i ; $ count ++ ; } } if ( $ n > 2 ) $ count ++ ; return ( $ count ) ; } function printKAlmostPrimes ( $ k , $ n ) { for ( $ i = 1 , $ num = 2 ; $ i <= $ n ; $ num ++ ) { if ( countPrimeFactors ( $ num ) == $ k ) { echo ( $ num ) ; echo ( " ▁ " ) ; $ i ++ ; } } return ; } $ n = 10 ; $ k = 2 ; echo " First ▁ $ n ▁ $ k - almost ▁ prime ▁ numbers : STRNEWLINE " ; printKAlmostPrimes ( $ k , $ n ) ; ? >