ProgrammingHard

Which method finds all primes up to 10^6 in time that is correct and fast enough?

  1. A. Trial division of each number by all smaller numbers, about 5 x 10^11 divisions
  2. B. Trial division with divisors up to the number itself, about 5 x 10^11 divisions
  3. C. A sieve of Eratosthenes with a char array of 10^6 + 1 flags, about O(n log log n)
  4. D. Trying every pair of numbers for a divisor, about 10^12 steps

Correct answer: C. A sieve of Eratosthenes with a char array of 10^6 + 1 flags, about O(n log log n)

The sieve touches each composite a small number of times. Trial division to n costs about n^2 / 4 divisions, which is far too slow at 10^6.

More C Programming questions

Exams that ask this topic