Suppose and are unsigned int variables in a C program. We wish to set to . If is large, which one of the following statements is most likely to set correctly?
View worked solution
Answer: B
To compute for a large unsigned integer , we must avoid two major issues in integer arithmetic:
- Integer Overflow: Computing the product first can easily exceed the maximum limit of an
unsigned int. - Truncation Error: Performing integer division when the numerator is not perfectly divisible by the denominator results in a loss of fractional parts.
Let's analyze each option:
-
Option A:
p = n * (n-1) * (n-2) / 6;
The product is evaluated first. For large , this will overflow theunsigned intrange before the division by 6 is performed, leading to an incorrect result. -
Option B:
p = n * (n-1) / 2 * (n-2) / 3;
- Out of two consecutive integers and , one must be even. Thus, is always divisible by . The division
n * (n-1) / 2is exact and does not lose any fractional part. - This intermediate value is . Since is mathematically an integer, the product is guaranteed to be divisible by . Thus, the final division by is also exact.
- Dividing by early significantly reduces the size of the intermediate product, making it highly resilient to overflow.
- Out of two consecutive integers and , one must be even. Thus, is always divisible by . The division
-
Option C:
p = n * (n-1) / 3 * (n-2) / 2;
The product is not always divisible by (e.g., if , , which is not divisible by ). Integer divisionn * (n-1) / 3will truncate the remainder, resulting in an incorrect final value. -
Option D:
p = n * (n-1) * (n-2) / 6.0;
The numerator is evaluated usingunsigned intarithmetic before being divided by the double constant6.0. Thus, it suffers from the exact same overflow issue as Option A.
Therefore, Option B is the most robust and correct statement.
Free practice · Your answers on this page are not saved.
