Last active
August 29, 2015 14:11
-
-
Save ssanin82/42a40438ab9d5202be68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def modinv(a, m): | |
orgm = m | |
x, lastx, y, lasty = 0, 1, 1, 0 | |
while m: | |
a, (quotient, m) = m, divmod(a, m) | |
x, lastx = lastx - quotient * x, x | |
y, lasty = lasty - quotient * y, y | |
if a != 1: | |
raise ValueError | |
return lastx % orgm | |
def fastcombmod(m, n, mod): | |
nn = min(n, m - n) | |
num = 1 | |
div = 1 | |
for i in xrange(nn): | |
num *= m - i | |
if num > mod: | |
num %= mod | |
div *= i + 1 | |
if div > mod: | |
div %= mod | |
return (num * modinv(div, mod)) % mod |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment