ProgrammingVery hard
To list all primes up to 10^7 in C with memory and time that fit, which is the best choice?
- A. Trial division of each number, about 10^14 steps
- B. A sieve with one bit per odd number, about 0.6 MB, and O(n log log n) time
- C. A sieve with one int per number, about 40 MB, and the same time
- 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
- For each of Q = 10^5 queries, a program sums an array prefix of length up to N = 10^5 by a loop. What is the total cost?
- A recurrence T(n) = T(n - 1) + n is solved by a program with a loop over the recursion. What is the total cost in terms of n?
- What is the total number of elements in a triangle of rows 1 to 10, where row k has k elements?
- A program runs a loop body 10^8 times and each iteration does one multiply and one add on ints. Roughly how long does this take on typical…
- A bit-packed bitset of 10^9 bits needs how much memory?
- Which loop is correct and fast enough to find the largest element of an array of 10^7 ints, reading each value once?