File tree Expand file tree Collapse file tree 3 files changed +44
-6
lines changed Expand file tree Collapse file tree 3 files changed +44
-6
lines changed Original file line number Diff line number Diff line change 1
1
#ifndef CP_ALGO_MATH_COMBINATORICS_HPP
2
2
#define CP_ALGO_MATH_COMBINATORICS_HPP
3
3
#include " common.hpp"
4
+ #include < cassert>
4
5
namespace cp_algo ::math {
5
6
template <typename T>
6
7
T binom_large (T n, int r) {
7
- assert (r < math:: maxn);
8
+ assert (r < maxn);
8
9
T ans = 1 ;
9
10
for (int i = 0 ; i < r; i++) {
10
11
ans = ans * T (n - i) * small_inv<T>(i + 1 );
@@ -15,10 +16,10 @@ namespace cp_algo::math {
15
16
T binom (int n, int r) {
16
17
if (r < 0 || r > n) {
17
18
return T (0 );
18
- } else if (n > math:: maxn) {
19
- return binom_large (n , r);
19
+ } else if (n >= maxn) {
20
+ return binom_large (T (n) , r);
20
21
} else {
21
- return math:: fact<T>(n) * math:: rfact<T>(r) * math:: rfact<T>(n- r);
22
+ return fact<T>(n) * rfact<T>(r) * rfact<T>(n - r);
22
23
}
23
24
}
24
25
}
Original file line number Diff line number Diff line change @@ -29,6 +29,8 @@ namespace cp_algo::math {
29
29
T bpow (T const & x, int64_t n) {
30
30
return bpow (x, n, T (1 ));
31
31
}
32
+ // fact/rfact/small_inv are caching
33
+ // Beware of usage with dynamic mod
32
34
template <typename T>
33
35
T fact (int n) {
34
36
static std::vector<T> F (maxn);
@@ -42,13 +44,15 @@ namespace cp_algo::math {
42
44
}
43
45
return F[n];
44
46
}
47
+ // Only works for modint types
45
48
template <typename T>
46
49
T rfact (int n) {
47
50
static std::vector<T> F (maxn);
48
51
static bool init = false ;
49
52
if (!init) {
50
- F[maxn - 1 ] = T (1 ) / fact<T>(maxn - 1 );
51
- for (int i = maxn - 2 ; i >= 0 ; i--) {
53
+ int t = std::min<int64_t >(T::mod (), maxn) - 1 ;
54
+ F[t] = T (1 ) / fact<T>(t);
55
+ for (int i = t - 1 ; i >= 0 ; i--) {
52
56
F[i] = F[i + 1 ] * T (i + 1 );
53
57
}
54
58
init = true ;
Original file line number Diff line number Diff line change
1
+ // @brief Binomial Coefficient (Prime Mod)
2
+ #define PROBLEM " https://judge.yosupo.jp/problem/binomial_coefficient_prime_mod"
3
+ #pragma GCC optimize("Ofast,unroll-loops")
4
+ #pragma GCC target("avx2,tune=native")
5
+ #define CP_ALGO_MAXN 1e7
6
+ #include " cp-algo/math/modint.hpp"
7
+ #include " cp-algo/math/combinatorics.hpp"
8
+ #include < bits/stdc++.h>
9
+
10
+ using namespace std ;
11
+ using namespace cp_algo ;
12
+ using namespace math ;
13
+ using base = dynamic_modint;
14
+
15
+ void solve () {
16
+ int n, r;
17
+ cin >> n >> r;
18
+ cout << binom<base>(n, r) << " \n " ;
19
+ }
20
+
21
+ signed main () {
22
+ // freopen("input.txt", "r", stdin);
23
+ ios::sync_with_stdio (0 );
24
+ cin.tie (0 );
25
+ int t = 1 ;
26
+ cin >> t;
27
+ int m;
28
+ cin >> m;
29
+ base::switch_mod (m);
30
+ while (t--) {
31
+ solve ();
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments