GATE / CS ARCHIVE

GATE CSE 2014 SET 2 / QUESTION 11

GATE CSE 2014 Set 2 Q11

Programming in C · Expressions, Operators & Types · Full GATE CSE 2014 Set 2 paper

GATE 2014 Set 2, Q11 1 mark · MCQ
Report issue

Expressions, Operators & Types

Question 11, GATE 2014: Unsigned int variables n and p are used in C to compute p=n choose 3. For large n, which statement is most likely to work correctly? A p=n*(n-1)*(n-2)/6; B p=n*(n-1)/2*(n-2)/3; C p=n*(n-1)/3*(n-2)/2; D p=n*(n-1)*(n-2)/6.0;
Tap to enlarge
Your answer
Answer & solution

Official answer: B

1. Set up the reasoning. Consider two separate hazards: overflow of intermediate unsigned products and truncation by integer division. Adjacent integers n and n-1 always have an even product, permitting an exact early division by two.

2. Derive the result. B divides the always-even product n(n−1) by 2 before multiplying by n−2, reducing intermediate magnitude without truncation. The final division by 3 is exact for the integer binomial product. A and D form the larger full product before division, while C may divide n(n−1) by 3 prematurely, truncating when n≡2 mod3. B is less overflow-prone, not guaranteed correct for arbitrarily large unsigned n; even its intermediate can wrap.

3. Check the interpretation. Multiplication and division associate left to right. The final floating divisor in D does not retroactively convert preceding integer products to floating point. B mitigates risk but cannot guarantee correctness for every representable n or for results too large to fit p.

Original paper, page 31 · Answer key