integer division properties
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.开发者_StackOverflow社区e. n > l
?
the question pertains to computer arithmetic, namely q = n/m, q*m != n
, ignoring overflow.
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)
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
精彩评论