Sieve of Eratosthenes

Find all primes from 2 through n. A prime has exactly two positive divisors, 1 and itself.

Cross out multiples of the selected prime p. A previously crossed number keeps its first divisor.

Start at p × p. Smaller multiples of p were already visited with smaller prime divisors.

For n numbers the sieve uses O(n) space and O(n log log n) time.