Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : Help with selection
Source : Codechef
Category : Combinatorics
Algorithm : Lucas Theorem
Verdict : Accepted
import math
def read():
return map(int, input().split())
def readAll():
return (int(i) for i in input().split())
fact = [0 for _ in range(1000000+5)]
def bigMod(a, p, m):
if p == 0:
return 1 % m
if p == 1:
return a % m
if p % 2 == 1:
return (a % m * bigMod(a, p - 1, m) % m) % m
ret = bigMod(a, p // 2, m)
return (ret %m * ret % m) % m
def modInverse(a, m):
return bigMod(a, m-2, m)
def nCr(n, r, mod):
if n < r:
return 0
temp = (fact[r] * fact[n-r]) % mod
temp = modInverse(temp, mod)
return (fact[n] * temp) % mod
def lucas(n, r, p):
if n == 0 and r == 0:
return 1
ni = n % p
ri = r % p
return (nCr(ni, ri, p) * lucas(n // p, r // p, p)) % p
def getAns(n, r, p):
fact[0] = 1
for i in range(1, p):
fact[i] = (i * fact[i-1]) % p
return lucas(n, r, p)
if __name__ == '__main__':
tc = int(input())
for tcase in range(1, tc+1):
n, r, p = readAll()
print(getAns(n, r, p))
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.