ProgrammingVery hard
A modular sum over 10^6 terms uses sum = (sum + a[i]) % MOD with a[i] < MOD and sum an int. What is wrong?
- A. sum + a[i] can reach about 2 x 10^9 and overflow int, so sum must be a long long or the addition reduced first
- B. The modulo operation is undefined for int
- C. Nothing, because int addition wraps safely
- D. The loop is too slow for 10^6 terms
Correct answer: A. sum + a[i] can reach about 2 x 10^9 and overflow int, so sum must be a long long or the addition reduced first
With MOD near 10^9, the sum of two values can exceed INT_MAX, which is undefined. A 64-bit sum avoids this.
More C Programming questions
- A counting loop uses the expression i i <= n with int i and n up to 2^31 - 1. Is the loop correct?
- To read a whole line of unknown length in standard C without overflow, which approach is correct?
- A program sums the digits of 10^5 numbers with one loop per number that divides by 10. What is the total cost, about?
- A queue for BFS on a grid of 10^6 cells uses a fixed array of size 10^6 indexed by head and tail. Is this enough?
- To find the maximum over 10^5 queries of ranges in a static array, which approach is fast enough?
- A program multiplies two n x n matrices with n = 500 in int, and the product entries reach about 10^12. What is the error?