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?

Choose one option
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.

  1. Mathematically:

    (n3)=n(n−1)(n−2)6.\binom{n}{3} = \frac{n(n-1)(n-2)}{6}.
  2. Analyze each option for large nn in 32-bit unsigned integer arithmetic:

    • Option A (p = n * (n-1) * (n-2) / 6):
      Multiplication has left-to-right associativity. The cubic product n(n−1)(n−2)n(n-1)(n-2) is evaluated first. For n>1625n > 1625, n3>232−1n^3 > 2^{32} - 1, causing 32-bit integer overflow even when (n3)\binom{n}{3} itself easily fits in an unsigned integer.
    • Option C (p = n * (n-1) / 3 * (n-2) / 2):
      n(n−1)n(n-1) is not necessarily divisible by 3 (e.g., if n≡2(mod3)n \equiv 2 \pmod 3, neither nn nor n−1n-1 is divisible by 3). In C, integer division / 3 truncates the fraction, yielding an incorrect result.
    • Option D (p = n * (n-1) * (n-2) / 6.0):
      The integer product n(n−1)(n−2)n(n-1)(n-2) 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 nn and n−1n-1 are two consecutive integers, one of them must be even. Therefore, n(n−1)n(n-1) is always divisible by 2, making n(n−1)/2n(n-1) / 2 mathematically exact without truncation. Furthermore, dividing by 2 immediately reduces the intermediate value, substantially delaying overflow. The subsequent multiplication by (n−2)(n-2) followed by / 3 is also exact because (n3)\binom{n}{3} is an integer.

Hence, option B is most likely to compute pp correctly.

Final answer

B

Common trap

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.