Modulo of a negative number

纵然是瞬间 提交于 2019-12-04 09:23:24

I don't want to bother you with some complex mathematical concepts, so i'll try to keep it simple. When we say that a = b (mod c), we simply say that a-b is a multiple of c. This means that when we want to know what is the value of a mod c, saying that it is a or a-c or a+c or a+1000*c is true. Thus, your 2 formulas are valid.

But what you want is to know the answer that a computer would give to you, right ? Well, it depends of the language you are using. With Java for example, a mod b has the sign of a and has is absolute value strictly inferior to b. This means that with a = 7, b = 3 and N = 5, (a-b)%N = 4, but your two expressions will return -1.

What I would suggest you to do if you want to do arithmetics with modulos is to create your own mod function, so it always give you a positive integer for example. This way, your 2 expressions will always be equal to the original one.

An example here in pseudocode :

function mod (int a, int N)
  return (a%N+N)%N
while(N < 0)
{
    N= N+MOD;
}

Or,
This will also work,

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