Per §15.17.3 "Remainder Operator %" of The Java Language Specification, Java SE 7 Edition, (a/b)*b+(a%b)
is always equal to a
. Turning this around, we have a%b == a - (a/b)*b
. So, you should be able to write:
power *= 2;
power -= (power/M) * M;
Or, since you're only multiplying by two each time, you know that power
cannot exceed M
before this operation, so you can rewrite the above as:
power *= 2;
if (power > M) {
power -= M;
}