How can I handle non-negative modes?

When I use the% operator in my Java programs, I get negative answers. Example: -1% 100 gives -1. Although it is mathematically correct, I want to get a 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 (maybe something I missed in Math?), I can not find it)?

I also want to clarify that if the API has something that does this, the link will be awesome.

+6
source share
4 answers

Can you just do it?

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

This should work for any positive d .

+3
source

You can do the following

 int myMod(int x, int modulo) { return ((x % modulo) + modulo) % modulo } 
+2
source

This works for any values ​​instead of d or x.

 int d=100; int x=-1%d; while (x<0) x+=d; 
0
source
 i < 0 ? n - ((-i - 1) % n + 1) : i % n 

For instance:

 class Mod { public static int mod(int i, int n) { return i < 0 ? n - ((-i - 1) % n + 1) : i % n; } public static void main(String [] args) { System.out.println("mod(-201, 100) == " + mod(-201, 100)); System.out.println("mod(-200, 100) == " + mod(-200, 100)); System.out.println("mod(17, 100) == " + mod(17, 100)); System.out.println("mod(100, 100) == " + mod(100, 100)); } } 

and

 $ javac Mod.java && java Mod mod(-201, 100) == 99 mod(-200, 100) == 0 mod(17, 100) == 17 mod(100, 100) == 0 

No cycles.

0
source

Source: https://habr.com/ru/post/899258/


All Articles