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.
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.
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.
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.
You can just do this?
int d = 100;
int x = -1 % d;
if (x < 0)
x += d;
This should work for any positive d
.
You can do the following
int myMod(int x, int modulo)
{
return ((x % modulo) + modulo) % modulo
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With