// A simple program to show how one must be careful // with the "mod" functions in some programming languages. // // Compile with "javac mod.java" and run with "java mod". // // The point here is that one expects that for any integer // a, and natural number n, one will get a "remainder" r // so that // a = q*n + r // for appropriate q and // 0 <= r < n. // // This works for positive values of a, but when a is negative, // the equations that hold turn out to be // a = q*n + r // and // -n < r <= 0. // // This is unsettling. In particular, the code // a%n == b%n // is not always true when a is congruent to b mod n. You need // to use this: // a%n == b%n || a%n == n + b%n public class mod{ public static void main(String[] args){ int a,r,n; n = 10; System.out.println("\nUsing build in modulo operation"); a = 11; r = a%n; System.out.println(a + " reduced modulo " + n + " is " + r); a = 1; r = a%n; System.out.println(a + " reduced modulo " + n + " is " + r); a = -9; r = a%n; System.out.println(a + " reduced modulo " + n + " is " + r); a = -19; r = a%n; System.out.println(a + " reduced modulo " + n + " is " + r); System.out.println("\nA Using integral division"); int q; a = 11; q = a/n; r = a - q*n; System.out.println(a + " reduced modulo " + n + " is " + r); a = 1; q = a/n; r = a - q*n; System.out.println(a + " reduced modulo " + n + " is " + r); a = -9; q = a/n; r = a - q*n; System.out.println(a + " reduced modulo " + n + " is " + r); a = -19; q = a/n; r = a - q*n; System.out.println(a + " reduced modulo " + n + " is " + r); System.out.println("\n Work-around using explicit round-down"); double aa, rr, qq, nn; nn = (double) n; a = 11; aa = (double) a; qq = Math.floor(aa/nn); rr = aa - qq*nn; r = (int) rr; System.out.println(a + " reduced modulo " + n + " is " + r); a = 1; aa = (double) a; qq = Math.floor(aa/nn); rr = aa - qq*nn; r = (int) rr; System.out.println(a + " reduced modulo " + n + " is " + r); a = -9; aa = (double) a; qq = Math.floor(aa/nn); rr = aa - qq*nn; r = (int) rr; System.out.println(a + " reduced modulo " + n + " is " + r); a = -19; aa = (double) a; qq = Math.floor(aa/nn); rr = aa - qq*nn; r = (int) rr; System.out.println(a + " reduced modulo " + n + " is " + r); System.out.println("\n A faster work-around"); a = 11; r = (a%n + n)%n; System.out.println(a + " reduced modulo " + n + " is " + r); a = 1; r = (a%n + n)%n; System.out.println(a + " reduced modulo " + n + " is " + r); a = -9; r = (a%n + n)%n; System.out.println(a + " reduced modulo " + n + " is " + r); a = -19; r = (a%n + n)%n; System.out.println(a + " reduced modulo " + n + " is " + r); } }