Modular Arithmetic

Binomial Coefficients Modulo a Prime: Fermat's Theorem and the Non-Adjacent Selection Problem

In the previous post, we implemented the closed form $F_{n,m} = \binom{n-m+1}{m}$ using Python’s math.factorial, and with scipy and sympy. Here we cover the common competitive-programming case: computing the answer modulo a large prime $M$ (e.g. $M = 10^9+7$).

Why modulo?

In counting problems, the result can be huge even for moderate input. Often the problem asks for the answer modulo a big prime so that it fits in a standard integer type. We could compute the full number and then take the remainder, but that forces expensive long-integer arithmetic. Computing everything modulo $M$ from the start is much faster.