1

Python "pow(n, k, m)" computes $n^k \pmod m$ efficiently, most likely by computing modulus after each squaring step.

I only found Python $binomial(n, k)$ function.
But computing that function for high values of $n$ and $k$ with only finally computing $\pmod m$ does not work.

Is there a method to compute ${n\choose{k}} \pmod m$ efficiently?
Or at least ${n\choose{k}} \pmod p$ with prime $p$?

I searched here and on Approach0 and found nothing helpful.

1 Answers1

0

If $n$ and $k$ are both $>> m$, Lucas' Theorem should be helpful. If not, there appears to be no efficient solution. What I did recently was to precompute factorials modulo $m$ and then $$(\mathrm{fact}(n) * \mathrm{pow}(\mathrm{fact}(k),-1,p) * \mathrm{pow}(\mathrm{fact}(n-k),-1,p))%p$$ It's not terribly efficient.

rogerl
  • 22,399
  • Thanks, but even for (big) prime $p$ that does not help for $n, k < p$ as you said.
    I am interested for prime $p=4k+1$ in computing:
    ${{2k}\choose k} \pmod p$ From here:
    https://math.stackexchange.com/a/45155/1084297
    – HermannSW Dec 21 '22 at 19:14
  • I would like to compute that for prime factors of RSA numbers, with 50+ digits. For 2nd prime factor 4k+1 =40094690950920881030683735292761468389214899724061 of RSA-100 sum of squares can be computed in sub second, but what about the binomial? – HermannSW Dec 21 '22 at 19:20
  • OK, so no efficient method for general integer modulus $m$, nor for prime modulus $p$ with $n,k < p$. But the first formula in posting I pointed to allows to efficiently compute ${{2k}\choose k}\pmod p$ with prime $p=4k+1$ with help of gaussian integer gcd: (1) $a=\sqrt(-1)\pmod p$ (2) $(x,y) = ggcd((p,0), (a,1))$ (3) ${{2k}\choose k}\pmod p = 2*x$. – HermannSW Dec 21 '22 at 23:40