When you perform many additions or multiplications, take mod after each operation. This keeps intermediate results small and prevents overflow.
Example: Compute (a + b + c) mod m. Do ((a + b) mod m + c) mod m. Or compute (a × b × c) mod m as ((a × b) mod m × c) mod m.
The modular properties guarantee the final answer is correct.