Skip to content

Commit 255cee9

Browse files
add binom (#20)
1 parent 0e64557 commit 255cee9

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// verification-helper: PROBLEM https://judge.yosupo.jp/problem/binomial_coefficient_prime_mod
2+
3+
use proconio::input;
4+
use programming_team_code_rust::binom::Binom;
5+
6+
fn main() {
7+
input! {
8+
t: usize,
9+
m: u64,
10+
}
11+
let mut binom = Binom::new(m);
12+
for _ in 0..t {
13+
input! {
14+
n: usize,
15+
k: usize,
16+
}
17+
println!("{}", binom.comb(n, k));
18+
}
19+
}

src/binom.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// n choose k for a prime modulo
2+
pub struct Binom {
3+
inv: Vec<u64>,
4+
fact: Vec<u64>,
5+
inv_fact: Vec<u64>,
6+
modulo: u64,
7+
}
8+
impl Binom {
9+
pub fn new(modulo: u64) -> Binom {
10+
Binom {
11+
inv: vec![1; 2],
12+
fact: vec![1; 2],
13+
inv_fact: vec![1; 2],
14+
modulo,
15+
}
16+
}
17+
pub fn comb(&mut self, n: usize, k: usize) -> u64 {
18+
assert!((n as u64) < self.modulo);
19+
if n < k {
20+
return 0;
21+
}
22+
while self.inv.len() <= n {
23+
let i = self.inv.len();
24+
self.inv.push(
25+
self.modulo
26+
- (self.modulo / i as u64) * self.inv[self.modulo as usize % i] % self.modulo,
27+
);
28+
self.fact.push(self.fact[i - 1] * i as u64 % self.modulo);
29+
self.inv_fact
30+
.push(self.inv_fact[i - 1] * self.inv[i] % self.modulo);
31+
}
32+
self.fact[n] * self.inv_fact[k] % self.modulo * self.inv_fact[n - k] % self.modulo
33+
}
34+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod binom;
12
pub mod dijk;
23
pub mod dsu;
34
pub mod fenwick;

0 commit comments

Comments
 (0)