When taking modulo of negative numbers makes sense?

与世无争的帅哥 提交于 2019-12-06 08:10:15

I needed to give a more complete answer.

As you say, mathematically makes sense (although, you don't need to be a mathematician to understand that), but let me clarify something. When I said you're interested in the residue, which it's true, one may be mistaken to think that residues for positive (a mod n) or negative (-a mod n) numbers are the same because one would naively drop the sign and carry on the division in the negative case. Of course, you now know this is not correct. You can think of it in this way: When calculating a mod n, first you find out which number n*x (where x is an integer) is closest to a without going over a. After that, you count how many number are there between n*x and a. An example is likely to help here:

Let's suppose you want -282 mod 10, then 10*-29 = -290 is closest to -282 without going over it. And then you simply count how many numbers are in between n*x and a (that is, between 290 and 282). There are 8 numbers, and that's your answer, which is correct. On the hand, for positive numbers (282 mod 10), the closest number to 282 will be 10*28 = 280 (remember, we don't want to go over 282). Therefore, there are 2 numbers in between (also correct).

As for the applications, I'm not sure about one application relying particularly in calculating modulo of negative numbers, but the whole field of Modular arithmetic provides a lot of applications. See the Wikipedia link above to read a bit about them. If it weren't for the mathematical consistency of having modulo operations of negative numbers, probably we would end up with less general theorems, which in turn means, less powerful applications.

With respect to your programming woes:

When either a or n is negative, this naive definition breaks down and programming languages differ in how these values are defined. Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands.

See also this.

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