Almost Prime Numbers | Python3 Program to print first n numbers that are k - primes ; 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
import math NEW_LINE def countPrimeFactors ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n / 2 ; NEW_LINE count += 1 ; NEW_LINE DEDENT i = 3 ; NEW_LINE while ( i <= math . sqrt ( n ) ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT n = n / i ; NEW_LINE count += 1 ; NEW_LINE DEDENT i = i + 2 ; NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT return ( count ) ; NEW_LINE DEDENT def printKAlmostPrimes ( k , n ) : NEW_LINE INDENT i = 1 ; NEW_LINE num = 2 NEW_LINE while ( i <= n ) : NEW_LINE INDENT if ( countPrimeFactors ( num ) == k ) : NEW_LINE INDENT print ( num , end = " " ) ; NEW_LINE print ( " ▁ " , end = " " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT num += 1 ; NEW_LINE DEDENT return ; NEW_LINE DEDENT n = 10 ; NEW_LINE k = 2 ; NEW_LINE print ( " First ▁ n ▁ k - almost ▁ prime ▁ numbers : " ) ; NEW_LINE printKAlmostPrimes ( k , n ) ; NEW_LINE