Suppose \(n\) and \(p\) are unsigned int variables in a C program. We wish to…
2014
Suppose \(n\) and \(p\) are unsigned int variables in a C program. We wish to set \(p\) to \(n_{C_3}\). If n is large, which one of the following statements is most likely to set \(p\) 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;\)
Attempted by 134 students.
Show answer & explanation
Correct answer: B
Correct expression: p = n * (n-1) / 2 * (n-2) / 3;
Why this ordering works:
Evaluation is left-to-right for multiplication and division, so the expression is computed as ((n*(n-1))/2)*(n-2)/3.
n*(n-1) is always even, so dividing by 2 is exact and loses no information.
After that division and multiplication by (n-2), the product of the three consecutive integers is divisible by 3, so the final division by 3 is also exact.
Because divisions happen early, intermediate values remain smaller and the chance of overflow in unsigned int is reduced.
Problems with the other forms:
Multiplying three numbers first (p = n*(n-1)*(n-2)/6) risks overflow before the division, producing a wrong result for large n.
Dividing by 3 too early (p = n*(n-1)/3*(n-2)/2) is unsafe because n*(n-1) may not be divisible by 3, so the integer division truncates and yields an incorrect result.
Using a floating constant (p = n*(n-1)*(n-2)/6.0) forces floating-point arithmetic, which can lose integer precision for very large values and lead to rounding when converting back to unsigned int.
Safer implementation tips:
Prefer the chosen integer ordering and, when n may be near the unsigned int limit, perform intermediate calculations in a wider integer type. Example: unsigned long long temp = (unsigned long long)n*(n-1)/2*(n-2)/3; p = (unsigned int)temp;
Alternatively, compute with a wider type all at once and divide at the end: p = (unsigned int)(((unsigned long long)n*(n-1)*(n-2))/6);
A video solution is available for this question — log in and enroll to watch it.