-1

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?

1 Answers1

0

The issue is that integer division is involved.

  • x*y >= z
  • x >= z / ((double)y)

Or integral an overflow would be for

  • x >= ceil(z / ((double)y))

Which is with integer division (truncating the remainder)

  • x >= (z + y - 1) / y

Or formulated differently: given z = m*y + n, where 0 <= n < y, then for n == 0 the division above will give m, otherwise m+1, the ceiling value. Below there is no overflow possible for x.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138