Write n and k in base p, multiply the small per-digit binomials C(n_i, k_i) mod p, and short-circuit to 0 the instant a digit k_i > n_i.
| step | cost |
|---|---|
| build fact/invFact (size p) | O(p) |
| one small binomial C(a,b) | O(1) |
| digit decomposition | O(log_p n) |
| full query C(n,k) mod p | O(p + log_p n) |
| plain factorial method | O(n) |
Lucas' theorem: for prime p, C(n,k) ≡ ∏_i C(n_i, k_i) (mod p) over the base-p digits.
A single factor of 0 (when k_i > n_i) makes the whole product 0.
Each small C(n_i, k_i) comes from a precomputed factorial table of size p.