Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle non-negative mods?

Tags:

java

modulo

When I use the operator % in my Java programs, I keep getting negative answers. Example: -1%100 gives -1. While this is mathematically correct, I want to get the normal mathematical solution, or 99. In other words, I want to get the smallest positive integer solution. Is there any simple solution for this in Java (perhaps something I overlooked in Math? -- I can't find it)?

I also want to clarify that if there is something in the API that does this, a link would be awesome.

like image 493
varatis Avatar asked Oct 13 '11 23:10

varatis


People also ask

How do you solve for a negative modulus?

The modulus of a negative number is found by ignoring the minus sign. The modulus of a number is denoted by writing vertical lines around the number. Note also that the modulus of a negative number can be found by multiplying it by −1 since, for example, −(−8) = 8.

Does mod work with negative numbers?

How does modulo work with negative numbers? When only the dividend is negative. When only the divisor is negative. When both the divisor and dividend are negative.

Can mod return negative?

These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results.


2 Answers

You can just do this?

int d = 100;

int x = -1 % d;
if (x < 0)
    x += d;

This should work for any positive d.

like image 149
Mysticial Avatar answered Oct 22 '22 14:10

Mysticial


You can do the following

int myMod(int x, int modulo)
{
   return ((x % modulo) + modulo)  % modulo
}
like image 40
Greg Adamski Avatar answered Oct 22 '22 13:10

Greg Adamski