Skip to content

Instantly share code, notes, and snippets.

@ssanin82
Last active August 29, 2015 14:12
Show Gist options
  • Save ssanin82/4f84fed2df8731af3993 to your computer and use it in GitHub Desktop.
Save ssanin82/4f84fed2df8731af3993 to your computer and use it in GitHub Desktop.
typedef long long ULONG;
typedef long long LONG;
inline LONG modinv(LONG a, LONG b) {
LONG b0 = b, t, q;
LONG x0 = 0, x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
if (!b) {
return -1;
}
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
inline ULONG fastcombmod(ULONG m, ULONG n, ULONG mod) {
ULONG nn = min(n, m - n);
ULONG num = 1;
ULONG div = 1;
for (int i = 0; i < nn; ++i) {
num *= m - i;
if (num > mod) {
num %= mod;
div *= i + 1;
} else {
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