Engineering Full Stack Apps with Java and JavaScript
According to mathematics, remainders are always positive. However, in java, when the remainder operation returns a nonzero result, it has the same sign as its left operand. Though most mathematicians won’t agree, Java Language Specification still refers to % as a remainder operator only.
While doing through hand, we can get same result as in java by division (of absolute values) through subtraction and then giving the sign of first operand.
In division by subtraction, we subtract divisor from dividend as long as dividend is bigger than divisor, the remaining dividend is the remainder and number of subtractions is the quotient.
For example, 14%3 can be done as 14-3-3-3-3, which gives 2 as remainder and 4 as quotient. Also, (14%-3) is 2, (-14%3) is -2 and (-14%-3) is -2. Note that the sign of remainder is same as that of first operand and sign of second operand doesn’t have any significance. Also note that absolute values are taken (signs are ignored) for division by subtraction.
A simple java program that does the same will be:
static int FindModulo(int divident, int divisor){
int abs_divident = Math.abs(divident);
int abs_divisor = Math.abs(divisor);
while(abs_divident>abs_divisor) {
abs_divident = abs_divident - abs_divisor;
}
return abs_divident*(divident/Math.abs(divident));
}
The actual division operation that JVM implement might be slightly different, but the above rules holds well for all.