Thursday, July 31, 2025

Binomial coefficients modulo m

I have recently written a Python function to compute binomial coefficients modulo m where m is a positive integer. It uses Lucas' theorem, Kummer's theorem, a generalization of Lucas' theorem for prime powers due to Davis and Webb [1], and the Chinese Remainder Theorem. The code is available as part of the pypi OEISsequences module: oeissequences · PyPI

After installing this modulo, it can be used as follows:

from oeis_sequences.OEISsequences import binom_mod
print(binom_mod(27449,13722,38)) # computes binomial(27449,13722) modulo 38 = 34
print(binom_mod(179424671,89712333,1062882)) # computes binomial(179424671,89712333) modulo 1062882 = 734832


This function is more efficient than computing the binomial coefficient (n,k) (using e.g., the Python function comb) and then taking the remainder with respect to m, especially when n and k are much larger than m and binomial(n,k) is a prohibitively large number. 

[1] Kenneth S. Davis and William A. Webb, "Lucas' Theorem for Prime Powers", Europ. J. Combinatorics (1990) 11, 229-233. 

No comments:

Post a Comment