7

does the following integer arithmetic property hold?

(m/n)/l == m/(n*l)

At first I thought I knew answer (does not hold), but now am not sure. Does it hold for all numbers or only for certain conditions, i.e. n > l?

the question pertains to computer arithmetic, namely q = n/m, q*m != n, ignoring overflow.

Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • Do you care about edge cases like overflows? Or wierd architectures/languages like those where `n/m` rounds down instead of toward zero? – Mooing Duck Apr 06 '15 at 18:45
  • [Is (a/b)/c equal to a/(b*c) for integer division?](https://math.stackexchange.com/q/2557458/90333) – phuclv Apr 17 '19 at 16:15
  • Possible duplicate of [Is it safe to replace "a/(b\*c)" with "a/b/c" when using integer-division?](https://stackoverflow.com/questions/45112911/is-it-safe-to-replace-a-bc-with-a-b-c-when-using-integer-division) – phuclv Apr 17 '19 at 16:15

2 Answers2

12
Case1 assume m = kn+b (b<n),
left = (m/n)/l = ((kn+b)/n)/l = (k+b/n)/l = k/l (b/n=0, because b<n)
right = (kn+b)/(n*l) = k/l + b/(n*l) = k/l (b/(n*l)=0, because b<n)
=> left = right

Case2 assume m = kn,
left = (m/n)/l = (kn/n)/l = k/l
right = kn/(n*l) = k/l
=> left = right

So, (m/n)/l == m/(n*l)
zs2020
  • 53,766
  • 29
  • 154
  • 219
5

Are you talking about mathematical integers? Or fixed-width integers within a programming language?

The two equations are identical with mathematical integers, but the two functions have different overflow behaviors if you are using fixed-width integers.

For example, suppose integers are 32-bit

(1310720000/65536)/65537 = 20000/65537 = 0

However, 65536 * 65537 will overflow a 32-bit integer, and will equal 65536, so

1310720000/(65536*65537) = 1310720000/65536 = 20000
Chi
  • 22,624
  • 6
  • 36
  • 37
  • +1 for beating me to it. And if I could, another +1 for apparently being the only responder to catch the word integer! – mtrw Apr 14 '10 at 03:14