I need to calculate nCr mod p
efficiently. Right now, I have written this piece of code, but it exceeds the time limit. Please suggest a more optimal solution.
For my case, p = 10^9 + 7 and 1 ≤ n ≤ 100000000
I have to also make sure that there is no overflow as nCr mod p
is guaranteed to fit in 32 bit integer, however n!
may exceed the limit.
def nCr(n,k):
r = min(n-k,k)
k = max(n-k,k)
res = 1
mod = 10**9 + 7
for i in range(k+1,n+1):
res = res * i
if res > mod:
res = res % mod
res = res % mod
for i in range(1,r+1):
res = res/i
return res
PS : Also I think my code may not be completely correct. However, it seems to work for small n
correctly. If its wrong, please point it out !