Mathematical approach to derive Modulo expression

Below are two expressions to find modulo(n,d) in java, using euclidean division

(d + (n % d))  if (n < 0)

(n%d)  if n > 0

My question is,

Am not clear, How to think mathematically before writing above expression, if n<0?

Please help me with mathematical approach, Because i do not want to remember logic!!!


If you want to remember what n % d does, it returns a value in the range (-d, d) congruent mod d to n and matching the sign of n.

If you want to know how to get a positive result (or strictly speaking, a result matching the sign of d instead of n), there's an easier way than the if .

Since (n % d) is in the range (-d, d) , that means (n % d) + n is in the range (0, 2d) , so ((n % d) + n) % d is a value in the range [0, d) , congruent to n.

Thus, ((n % d) + n) % d is what you're looking for.

链接地址: http://www.djcxy.com/p/58292.html

上一篇: 试图更好地理解模计算

下一篇: 推导模态表达式的数学方法