取模运算在数学定义与机器理解的区别

2019-04-13 12:57发布

纪念我c语言第一次课堂作业被坑 取模运算(“MOD”) 数学定义: 谷歌到《Concrete Mathematics》上的一段,原文:

摘自P82:

3.4 ‘MOD’: THE BINARY OPERATION
The quotient of n divided by m is [n/m],when m and n are positive
integers. It’s handy to have a simple notation also for the remainder
of this division, and we call it ‘n mod m’, The basic formula
n = m[n/m]+ n mod m
//NOTE:”m[n/m]” is quotient, “n mod m” is remainder
tells us that we can express n mod m as n-m[n/m] .We can generalize this
to megative integers, and in fact to arbitrary real numbers:

x mod y = x - y[x/y], for y!=0.

在这里的余数(Remainder)其实就是取模(mod):x mod y=x % y=x-y(x/y),for y!=0.

在概念上数和机器的理解是相同的,然鹅……机器在实现上确是与数学有差异。 1.数学上:[x/y]为x/y的最小下界
举个栗子:
5 mod 2=5 - 2 * [5/2]
=5 - 2 * [2.5]
=5 - 2 * 2
=1
2.机器上:[x/y]=(x/y)其实就是取余
再举个栗子:
5 mod 2 = 5 - 2 * [5/2]
=5 - 2 * (5/2)
=5 - 2 * (2)
=5 - 2 * 2
=

总结:so……以后在用代码实现时要千万记住:mod 是 % 是 取模 取模 取模!

公式:x mod y = x % y = x - y(x/y),for y!=0