Combinatorics
Basics of counting
Binomial coefficient patterns: “choose the positions”
When you need to place identical “special markers” into distinct slots (or choose which items are special), the count is
Classic example: number of binary strings of length with exactly ones is (choose the positions of the ones).
Practice
Computing with factorials + inverse factorials (mod prime)
Many problems may require you to compute many instances of for a fixed prime (commonly ).
We use:
and modular inverses (division mod ).
Fermat inverse (prime modulus)
If is prime and , then:
Precomputation plan
Let be the maximum we will need.
- Precompute
fact[i] = i! mod pfor - Precompute
invfact[i] = (i!)^{-1} mod pfor - use binary exponentiation to compute the powers. - Then each query is :
Practice
Stars and Bars
Core statement
Number of solutions in nonnegative integers to
is
Common variations
- If , substitute :