Here you can find the source of mod(final int dividend, final int divisor)
public static int mod(final int dividend, final int divisor)
//package com.java2s; public class Main { /**/*from w w w.j a v a 2s . c o m*/ * Java's modulus operator is disappointingly different to other languages. I wanted to take a * number and corral it into the range 0 ... divisor which you can do with a % in Python. However, * in Java you get the 'wrong' answer for negative dividends. So the hack is to add (n * divisor) * to the dividend to make it positive. */ public static int mod(final int dividend, final int divisor) { assert divisor > 0 : "have not implemented negative divisors yet"; int dividend2 = dividend; if (dividend2 < 0) { int makePositive = (1 + -1 * dividend2 / divisor) * divisor; dividend2 = dividend2 + makePositive; } return dividend2 % divisor; } }