Check out the Sieve of Eratosthenes. en.wikipedia.org/wiki/Sieve_of_Eratosthenes