% performs a remainder operation in Java.
To get the correct module, you can use the remainder in the function:
This is the shortest use of the ternary operator to fix the sign:
private int mod(int x, int y)
{
int result = x % y;
return result < 0? result + y : result;
}
For those who don't like the ternary operator, this is equivalent to:
private int mod(int x, int y)
{
int result = x % y;
if (result < 0)
result += y;
return result;
}
source
share