ProgrammingVery hard
To compute the sum of 1 through n = 10^9 without overflow in C, which code is correct?
- A. int n = 1000000000; int s = n * (n + 1) / 2;
- B. unsigned long long n = 1000000000ULL; unsigned long long s = n * (n + 1) / 2;
- C. int n = 1000000000; long s = n * (n + 1) / 2 with a loop of n steps
- D. unsigned int n = 1000000000; unsigned int s = n * (n + 1) / 2;
Correct answer: B. unsigned long long n = 1000000000ULL; unsigned long long s = n * (n + 1) / 2;
Multiplying as unsigned long long keeps n * (n + 1) = 10^18 + 10^9 inside range and the result 5 x 10^17 fits. int overflows, and a 32-bit unsigned int overflows too.
More C Programming questions
- 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…
- A 2 x 2 matrix is raised to the power 10^18 by repeated squaring. How many squaring steps are needed?