-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComb.java
More file actions
59 lines (50 loc) · 1.77 KB
/
Copy pathComb.java
File metadata and controls
59 lines (50 loc) · 1.77 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Shunta の自作ライブラリ
// https://github.com/NAVYSHUNTA/atcoder-shunta-library/blob/main/math/comb/java/Comb.java
import java.math.BigDecimal;
// 組合せクラス
class Comb {
private long mod = 0L;
private BigDecimal[] f;
private long[] fac;
private long[] facInv;
private long[] inv;
// O(n): コンストラクタ
Comb(int n) {
this.f = new BigDecimal[n + 1];
this.f[0] = BigDecimal.ONE;
for (int i = 1; i <= n; i++) {
this.f[i] = this.f[i - 1].multiply(BigDecimal.valueOf(i));
}
}
// O(n): コンストラクタ
Comb(int n, int mod) {
this.mod = mod;
this.fac = new long[n + 1];
this.facInv = new long[n + 1];
this.inv = new long[n + 1];
this.fac[0] = 1L;
this.fac[1] = 1L;
this.facInv[0] = 1L;
this.facInv[1] = 1L;
this.inv[0] = 1L;
this.inv[1] = 1L;
for (int i = 2; i <= n; i++) {
this.fac[i] = (this.fac[i - 1] * i) % mod;
this.inv[i] = ((-this.inv[mod % i] * (mod / i)) % mod + mod) % mod;
this.facInv[i] = ((this.facInv[i - 1] * this.inv[i]) % mod + mod) % mod;
}
}
// nCr の値を求めるメソッド
// O(1): コンストラクタで mod を指定していないかつ n が小さい場合
// O(1): コンストラクタで mod を指定している場合(n の値によらない)
public long getComb(int n, int r) {
if (n < r || Math.min(n, r) < 0) {
return 0L;
}
if (mod >= 1L) {
return (((this.fac[n] * this.facInv[r]) % this.mod) * this.facInv[n - r]) % this.mod;
} else {
return this.f[n].divide(this.f[r].multiply(this.f[n - r])).longValue();
}
}
}