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?
- A. int s = n * (n + 1) / 2;
- B. long long s = (long long)n * (n + 1) / 2;
- C. long long s = n * (n + 1) / 2 with n as int, which overflows
- 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
- Which condition makes a loop with an int index i and a sizet bound n safe from an infinite loop when n is 0?
- A loop does for (int i = 1; i <= n; i++) { x = i / 2; } with n = 10^9. What is the main cost concern?
- Which tool gives the fastest I/O in C for up to 10^6 integers in a contest setting?
- Each of 10^5 insertions into a dynamic array takes an O(n) memmove to keep the array sorted. Which total cost is right?
- A program uses a 2D table of size 1000 x 1000 with an O(1) update per cell and 1000 passes. How many cell updates are done?
- The number of comparisons a merge of two sorted arrays of sizes 4 and 6 makes in the worst case is at most?