integer division properties

时光总嘲笑我的痴心妄想 提交于 2020-01-02 02:54:32

问题


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.


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/2634546/integer-division-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!