Rewrite algoritm in PrimeGen