A suggestion for an alternative algorithm: Sieve of Eratosthenes - Wikipedia, the free encyclopedia, perhaps compare the complexity of that algorithm vs the nested look you posted in the original...