A k-Almost-prime number is a natural numberA curious thing about its Python code is that I had to introduce a name terms for a partial result:n, that is the exact multiple ofkprimes.

So, for example if k is 1, then this is the series of prime numbers themselves. If k is 2 then this is the series of semiprimes.

The task is to write a function/method/subroutine/... that generates k-almost primes and use it to create a table of the first ten members of k-Almost primes for 1 < =K< = 5.

```
from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [d.next() for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
```

#### Output:

### StopIteration swallowing

The following will not work as any StopIteration exception raised by trying to pull more prime decomposition values from the decompose operator will just stop the iterator when we need the exception to propagate to the except clause and so return False:return reduce(int.__mul__,

(d.next() for i in range(k)), 1) == n

So, you should just stop monkeying around and use islice like the normal folks. :-)

ReplyDelete