ProgrammingVery hard

To list all primes up to 10^7 in C with memory and time that fit, which is the best choice?

  1. A. Trial division of each number, about 10^14 steps
  2. B. A sieve with one bit per odd number, about 0.6 MB, and O(n log log n) time
  3. C. A sieve with one int per number, about 40 MB, and the same time
  4. D. A nested loop comparing every pair of numbers, about 10^14 steps

Correct answer: B. A sieve with one bit per odd number, about 0.6 MB, and O(n log log n) time

A bit-packed sieve over odd numbers uses about 10^7 / 16 bytes, about 0.6 MB, and runs in O(n log log n). The int-per-number sieve is correct but about 40 MB, and the others are far too slow.

More C Programming questions

Exams that ask this topic