code: public static int mod(int x, int m) {
      if (m <= 0) {
        throw new ArithmeticException("Modulus " + m + " must be > 0");
      }
      int result = x % m;
      return (result >= 0) ? result : result + m;
    }
docs: Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x %
  m}, which might be negative.
  
  <p>For example:
  
  <pre>{@code
  mod(7, 4) == 3
  mod(-7, 4) == 1
  mod(-1, 4) == 3
  mod(-8, 4) == 0
  mod(8, 4) == 0
  }</pre>
  
  @throws ArithmeticException if {@code m <= 0}
  @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
  Remainder Operator</a>