ProgrammingHard
Which method finds all primes up to 10^6 in time that is correct and fast enough?
- A. Trial division of each number by all smaller numbers, about 5 x 10^11 divisions
- B. Trial division with divisors up to the number itself, about 5 x 10^11 divisions
- C. A sieve of Eratosthenes with a char array of 10^6 + 1 flags, about O(n log log n)
- 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
- Binary search on the answer: a monotone check runs in O(n) and the answer lies in [1, 10^9]. What is the total complexity?
- A recursive naive Fibonacci fib(n) makes calls(n) = calls(n-1) + calls(n-2) + 1 with calls(0) = calls(1) = 1. Roughly how many calls does…
- A loop computes the number of decimal digits of n = 10^18 with while (n) { n /= 10; cnt++; }. What value does cnt reach?
- Trial division factorises a number up to 10^12 with for (i = 2; i i <= n; i++) while (n % i == 0) n /= i;. About how many outer iterations…
- A 2 x 2 matrix is raised to the power 10^18 by repeated squaring. How many squaring steps are needed?
- Which statement about the nested loop for (i = 0; i < n; i++) for (j = 1; j < n; j = 2) is correct?