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.
source share