Multiply, then mod
transcript
A times B, then mod. The program prints a wrong answer. Both numbers are ints in Java. Small test numbers pass. Big ones fail without any error.
Take a and b equal to one hundred thousand. The product is ten billion. A thirty two bit int cannot hold it. It wraps to this number. The right remainder is 999,999,937. Java prints a different number.
Widen to long before you multiply. Reduce after every step. And add the modulus back if a remainder is negative.
JavaScript has no int. Its numbers are doubles. A double is exact only up to two to the fifty three. Residues near a billion lose digits. Use BigInt. Each language fails in its own way. Widen before you multiply.
Subtraction can go negative. Take three minus five, mod seven. Python gives five. Java, C plus plus and JavaScript give minus two. Add the modulus, then take the remainder again.
Same rule, any input. Full breakdown in the lecture.