Why answers are “mod 10⁹ + 7”
Counts can grow astronomically, so problems ask for the answer mod 10⁹+7. Take the mod after every + and ×, not just at the end.
The idea
Counting problems (number of ways, paths, strings) often have answers with hundreds of digits. To keep numbers small, the problem asks for the remainder mod 10⁹ + 7, a large that fits in 32 bits.
The rules that make it work: (a + b) % m = ((a % m) + (b % m)) % m, and the same for ×. So you can reduce after every step and the final remainder is still right. Subtraction needs care: (a − b) % m can go negative in Java/C++, so add m first.
Worked example
Ways to climb n stairs, mod 10⁹ + 7
- ways(i) = ways(i − 1) + ways(i − 2): , which grows past 64 bits around n = 93.
- Store (ways(i − 1) + ways(i − 2)) % MOD at every step instead.
- Every value stays below 10⁹ + 7, and the answer matches the true count's remainder.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
n = 7
Solution · Pythonline 4
MOD = 10**9 + 7 def count_ways(n):a, b = 1, 1for _ in range(n - 1):a, b = (a + b) % MOD, areturn a def mul_mod(a, b):return (a % MOD) * (b % MOD) % MODStep 1 of 8· line 4
ways(i) = ways(i − 1) + ways(i − 2) grows like Fibonacci and overflows 64 bits around i = 93. Taking % MOD at every step keeps each value small, and the final remainder is still right.
Same as without the mod; each step adds an remainder.
How to spot it
- “Return the answer 10⁹ + 7.” It's a hint the answer is a huge count, usually from DP or combinatorics.
Common mistakes
- Taking the mod only at the end: in Java/C++ the intermediate values already overflowed.
- Dividing under a mod: you can't just divide; you need a modular inverse (see the fast power tip).
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →