[Geeks for Geeks] nCr

nCr

Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7

  • Time : O(n log mod)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define ll long long
class Solution{
ll fact[1001];
ll inv[1001];
ll mod = 1e9 + 7;
ll fac(ll n) {
if(fact[n] != -1) return fact[n];
return fact[n] = (n * fac(n-1)) % mod;
}
ll modpow(ll x, ll n) {
if(n == 0) return 1;
ll res = modpow(x, n>>1);
res = (res * res) % mod;
if(n & 1) res = (res * x) % mod;
return res;
}
ll inve(ll n) {
if(inv[n] != -1) return inv[n];
return inv[n] = (modpow(n, mod - 2) * inve(n-1)) % mod;
}
public:
int nCr(int n, int r){
if(n < r) return 0;
memset(fact, -1, sizeof fact);
memset(inv, -1, sizeof inv);
inv[0] = fact[0] = inv[1] = fact[1] = 1;
return (((fac(n) * inve(r)) % mod) * inve(n-r)) % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/ncr/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.