Fix inv_mod_xn

This commit is contained in:
wborgeaud 2022-03-20 07:23:51 +01:00
parent 7d6c0a448d
commit 6a6414163a
2 changed files with 13 additions and 2 deletions

View File

@ -86,8 +86,14 @@ impl<F: Field> PolynomialCoeffs<F> {
/// Computes the inverse of `self` modulo `x^n`.
pub fn inv_mod_xn(&self, n: usize) -> Self {
assert!(n > 0, "`n` needs to be nonzero");
assert!(self.coeffs[0].is_nonzero(), "Inverse doesn't exist.");
// If polynomial is constant, return the inverse of the constant.
if self.degree_plus_one() == 1 {
return Self::new(vec![self.coeffs[0].inverse()]);
}
let h = if self.len() < n {
self.padded(n)
} else {

View File

@ -528,10 +528,15 @@ mod tests {
let mut rng = thread_rng();
let a_deg = rng.gen_range(1..1_000);
let n = rng.gen_range(1..1_000);
let a = PolynomialCoeffs::new(F::rand_vec(a_deg));
let mut a = PolynomialCoeffs::new(F::rand_vec(a_deg));
if a.coeffs[0].is_zero() {
a.coeffs[0] = F::ONE; // First coefficient needs to be nonzero.
}
let b = a.inv_mod_xn(n);
let mut m = &a * &b;
m.coeffs.drain(n..);
if m.coeffs.len() > n {
m.coeffs.drain(n..);
}
m.trim();
assert_eq!(
m,