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?
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2014 Set 2 · Q11
Time
n and p are unsigned int variables in a C program. We wish to set p to . If n is large, which one of the following statements is most likely to set p correctly?Select one answerSingle correct
Solution
Official answer: B) p = n * (n-1) / 2 * (n-2) / 3;
Programming in CWe need to compute:
When is large, computing the product directly will easily cause integer overflow before the division by 6 is performed.
Let's evaluate each option:
(A)p = n * (n-1) * (n-2) / 6;: Computes the full 3-term product first, which is most vulnerable to integer overflow.
(B)p = n * (n-1) / 2 * (n-2) / 3;:
One of or is always even, so is always divisible by 2. Thus, integer division n * (n-1) / 2 loses no precision and yields an exact integer.
The product of any three consecutive integers is divisible by 6. Since division by 2 was performed first without remainder, the remaining factor must be divisible by 3. Thus, ... * (n-2) / 3 also divides evenly with no fractional loss.
Performing the division early keeps intermediate values smaller, preventing overflow.
(C)p = n * (n-1) / 3 * (n-2) / 2;: is not necessarily divisible by 3 (for instance, if , , and truncates the fractional part), resulting in an incorrect answer.
(D)p = n * (n-1) * (n-2) / 6.0;: The integer expression n * (n-1) * (n-2) is still evaluated first in unsigned int arithmetic before promotion to double, so overflow still happens.
Therefore, (B) is the correct statement.
Try the question first, then check your work.
Examiner trap
Consider integer division truncation and intermediate overflow for large . Between any two consecutive integers, at least one is divisible by 2.
This Programming in C previous year question is Q11 of the GATE CSE 2014 Set 2 paper. Find more GATE CSE PYQs on Programming in C in Programming and Data Structures, or browse all GATE CSE PYQs.
Free diagnostic
Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Programming in C PYQs now with no account.
An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.
Programming in C has 74 GATE CSE PYQs across 25 papers from 2011 to 2026. 20 of them are 1-mark MCQs like this one, and GATE CSE 2014 Set 2 has 2.
How GATE tests Programming in CIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.