Skip to main content

取余和取模

取余和取模

取模运算(Modulus Operation)和取余运算(Remainder Operation)两个概念有重叠的部分但又不完全一致。主要的区别在于对负整数进行除法运算时操作不同。取模主要是用于计算机术语中。取余则更多是数学概念。

对于整型数 x, y 来说,取模运算或者求余运算的方法都是:

  1. 求 整数商: q = x/y
  2. 计算模或者余数: r = x - y*q

    求余和取模在第一步不同:rem 使用 fix 函数(向最靠近零取整,即向 0 方向舍入),mod 使用 floor 函数(向下取整,即向负无穷方向舍入)

e.g.
-7/4
商 -1 余 -3
商 -2 模 1

%C/C++、Java、Go 中为取余,而在 Python 中为取模

所以,在使用不同语言时,要注意 /% 的区别

运算符优先级

网上的博客都说在 Go 中加减比移位优先级高,我动手验证了一下,并非如此。每一门编程语言都有些差异,网上的博客不一定可信。
2 + 2>>1 在 Java、Python 中结果为 2,而在 Go 中结果为 3

查阅官方文档:

Precedence    Operator
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||

数组拆分

分页 length := (len(input) + size - 1) / size

func Segments(input []int64, size int) [][]int64 {
if len(input) <= size {
return [][]int64{input}
}
length := (len(input) + size - 1) / size
segments := make([][]int64, 0, length)
for i := 0; i < length-1; i++ {
segments = append(segments, input[i*size:(i+1)*size])
}
segments = append(segments, input[(length-1)*size:])
return segments
}

参考资料

  1. 取模运算
  2. Operator precedence