ProgrammingVery hard
Which method is correct and fast enough for n choose r modulo p = 10^9 + 7 for 10^6 queries with n up to 10^6?
- A. Precompute factorials and inverse factorials in O(N), then each query is O(1) using modular inverses
- B. Build the full Pascal triangle up to n = 10^6, which needs about 5 x 10^11 cells
- C. Compute n! from scratch with a loop for every query, about 10^12 steps
- D. Recurse on Pascal's rule without memoisation for each query
Correct answer: A. Precompute factorials and inverse factorials in O(N), then each query is O(1) using modular inverses
Factorials cost O(N) once and each query is a few multiplications plus one modular power. The Pascal table would need on the order of 5 x 10^11 cells.
More C Programming questions
- To compute the sum of 1 through n = 10^9 without overflow in C, which code is correct?
- Which method finds all primes up to 10^6 in time that is correct and fast enough?
- 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…