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)?
- A. n * (n + 1) * (2 * n + 1) / 6 computed in 64-bit arithmetic
- B. n * (n + 1) / 2 computed in 32-bit arithmetic
- C. n * n * n / 3 computed in 32-bit arithmetic
- 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
- Which operation on a dynamic array of n elements has O(1) amortised cost when using doubling?
- A loop does for (i = n; i > 0; i /= 2) for (j = 0; j < i; j++) work();. For n = 1024, how many times is work() called in total?
- Which of these is an O(n) method to test whether a string of length n is a palindrome in C?
- char s[] = "hello world"; char w = strchr(s, ' ') + 1; printf("%s", w); What is printed?
- char a[8] = "abc"; memset(a + 1, 'z', 2); printf("%s", a); What is printed?
- char s[] = "12abc"; char end; long v = strtol(s, &end, 10); printf("%c", end); What is printed?