Question
Suppose n and p are unsigned int variables in a C program. We wish to set p to nC3. If n is large, which one of the following statements is most likely to set p correctly?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2014 answer key
Solution
Analyze operator associativity and integer overflow in computing nC3 for large n.
-
Mathematically:
-
Analyze each option for large in 32-bit unsigned integer arithmetic:
- Option A (
p = n * (n-1) * (n-2) / 6):
Multiplication has left-to-right associativity. The cubic product is evaluated first. For , , causing 32-bit integer overflow even when itself easily fits in an unsigned integer. - Option C (
p = n * (n-1) / 3 * (n-2) / 2):
is not necessarily divisible by 3 (e.g., if , neither nor is divisible by 3). In C, integer division/ 3truncates the fraction, yielding an incorrect result. - Option D (
p = n * (n-1) * (n-2) / 6.0):
The integer product still overflows before the floating-point conversion, and floating-point assignment can cause precision loss. - Option B (
p = n * (n-1) / 2 * (n-2) / 3):
Since and are two consecutive integers, one of them must be even. Therefore, is always divisible by 2, making mathematically exact without truncation. Furthermore, dividing by 2 immediately reduces the intermediate value, substantially delaying overflow. The subsequent multiplication by followed by/ 3is also exact because is an integer.
- Option A (
Hence, option B is most likely to compute correctly.
B
Assuming option A is safe because division by 6 is at the end, overlooking intermediate product overflow.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 2
- Question
- 21 of 65, printed as CS Q.11
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.