ProgrammingHard

For n = 10^6, which C code computes the sum of the first n integers in O(1) without overflow in 64-bit long long?

  1. A. int s = n * (n + 1) / 2;
  2. B. long long s = (long long)n * (n + 1) / 2;
  3. C. long long s = n * (n + 1) / 2 with n as int, which overflows
  4. D. int s = n * n / 2 + n / 2;

Correct answer: B. long long s = (long long)n * (n + 1) / 2;

Casting n to long long before the multiplication avoids overflow. Multiplying in int overflows for n near 10^5 and above with the product.

More C Programming questions

Exams that ask this topic