nekolib/math/
interpolation.rs1use super::const_div;
4use super::gcd_recip;
5
6use const_div::ConstDiv;
7use gcd_recip::GcdRecip;
8
9pub struct Interpolation {
35 first: Vec<u64>,
36 fact_recip: Vec<u64>,
37 cd: ConstDiv,
38 modulo: u64,
39}
40
41impl Interpolation {
42 pub fn with(first: Vec<u64>, modulo: u64) -> Self {
43 let n = first.len();
44 let cd = ConstDiv::new(modulo);
45 let r = (2..n as u64).reduce(|x, y| cd.rem(x * y)).unwrap_or(1);
46 let mut fact_recip = vec![1; n];
47 fact_recip[n - 1] = r.gcd_recip(modulo).1;
48 for i in (2..n).rev() {
49 fact_recip[i - 1] = cd.rem(fact_recip[i] * i as u64);
50 }
51 Self { first, fact_recip, cd, modulo }
52 }
53 pub fn interpolate(&self, x: u64) -> u64 {
54 if (x as usize) < self.first.len() {
55 return self.first[x as usize];
56 }
57 let cd = self.cd;
58 let modulo = self.modulo;
59 let n = self.first.len() - 1;
60 let omega = (0..=n as u64)
62 .map(|i| cd.rem(x + modulo - i))
63 .reduce(|acc, x| cd.rem(acc * x))
64 .unwrap();
65 let sigma: u64 = (0..=n)
66 .map(|i| {
67 let wi = cd.rem(self.fact_recip[i] * self.fact_recip[n - i]);
68 let sgn = if (n - i) % 2 != 0 { modulo - wi } else { wi };
69 let tmp = cd.rem(self.first[i] * sgn);
70 tmp * (x + modulo - i as u64).gcd_recip(modulo).1
71 })
72 .sum();
73 cd.rem(omega * cd.rem(sigma))
74 }
75}