ProgrammingVery hard

Which code gives the correct sum of the first n squares, for n up to 10^6, using a closed form in O(1)?

  1. A. n * (n + 1) * (2 * n + 1) / 6 computed in 64-bit arithmetic
  2. B. n * (n + 1) / 2 computed in 32-bit arithmetic
  3. C. n * n * n / 3 computed in 32-bit arithmetic
  4. D. n * (n - 1) / 2 computed in 64-bit arithmetic

Correct answer: A. n * (n + 1) * (2 * n + 1) / 6 computed in 64-bit arithmetic

The formula sum k^2 = n(n+1)(2n+1)/6 is exact. For n = 10^6 the product is about 2 x 10^18, which fits in signed 64-bit, but not 32-bit.

More C Programming questions

Exams that ask this topic