Math Fundamentals18 sections · 814 units
Open in Course

Overflow Prevention

(Why mod is not optional)

Without mod, multiplying two numbers near 10^9 gives a result near 10^18, which overflows a 32-bit int. Even 64-bit long can overflow if you multiply three large numbers.

By taking mod after each operation, you keep values under 10^9, which fits comfortably in 32 bits. The modular properties guarantee the final answer is correct.

If you forget mod, your code will produce wrong answers on large inputs.