ProgrammingVery hard

To compute the sum of 1 through n = 10^9 without overflow in C, which code is correct?

  1. A. int n = 1000000000; int s = n * (n + 1) / 2;
  2. B. unsigned long long n = 1000000000ULL; unsigned long long s = n * (n + 1) / 2;
  3. C. int n = 1000000000; long s = n * (n + 1) / 2 with a loop of n steps
  4. 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

Exams that ask this topic