Semi-Primes
September 6, 2019
We have on several occasions seen functions for generating the primes less than n. Sometimes, what you want instead of primes are semi-primes, numbers which are the product of two primes. For instance, the six semi-primes less than 25 are 2×3=6, 2×5=10, 2×7=14, 3×5=15, 3×7=21 and 2×11=22.
Your task is to write a function that makes a list of the semi-primes less than n; use it to discover the number of semi-primes less than 10,000. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Python. The semiprimes are generated in order.
An faster version in Python. The Python sort function is very efficient for a sequence of runs of already sorted items, so there is no point in using merge.
bool isPrime(int n)
{
if (n <= 1)
return false;
Here’s some Haskell, making use of lazy lists:
All those merges build up in memory, but we can find eg. 5111663, the 1000000th semiprime without too much trouble in 30 seconds or so.
If we include the squares of primes in the semiprimes, the code is even simpler: