The following code is using some integer overflow preventation trick that I'm trying to understand:
// x,y,z are positive numbers
boolean check(long x, long y, long z) {
return x >= (z+y-1)/y;
}
Based on the problem definition, I assume that the actual intent for the code is:
return x*y >= z;
Looks like the author avoids integer overflow with following line of thought:
1. x*y >= z
2. x >= z / y //Divide both sides by y
3. x - 1 >= (z - 1) / y //Subtract 1 from left side and dividend
4. x >= (z - 1) / y + 1 //Move 1 to the right side
5. x >= (z + y - 1) / y //Place 1 inside the brackets
Point 3 is what I'm trying to understand.
The second inequality is not identical to the original intent(take for example x=10, y=10, z=101), but third point serves as a workaround(based on my tests).
Can you please explain the theory behind this?