IntermediateMath for DSADynamic Programming

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

  1. ways(i) = ways(i − 1) + ways(i − 2): , which grows past 64 bits around n = 93.
  2. Store (ways(i − 1) + ways(i − 2)) % MOD at every step instead.
  3. 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.

MOD ← 1 000 000 007
a, b ← 1, 1
repeat n − 1 times:
a, b ← (a + b) % MOD, a(reduce at every step)
return a
products: (a % MOD) × (b % MOD) % MOD

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

n = 7

a = 1b = 1

Solution · Pythonline 4

MOD = 10**9 + 7
def count_ways(n):
a, b = 1, 1
for _ in range(n - 1):
a, b = (a + b) % MOD, a
return a
def mul_mod(a, b):
return (a % MOD) * (b % MOD) % MOD

Step 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

Where it comes up

Go further