Skip to content

refactor DensePolynomial add #905

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 20, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 26 additions & 23 deletions poly/src/polynomial/univariate/dense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,32 +284,35 @@ impl<'a, F: Field> Add<&'a DensePolynomial<F>> for &DensePolynomial<F> {
type Output = DensePolynomial<F>;

fn add(self, other: &'a DensePolynomial<F>) -> DensePolynomial<F> {
let mut result = if self.is_zero() {
other.clone()
} else if other.is_zero() {
self.clone()
} else if self.degree() >= other.degree() {
let mut result = self.clone();
result
.coeffs
.iter_mut()
.zip(&other.coeffs)
.for_each(|(a, b)| {
*a += b;
});
result
// If the first polynomial is zero, the result is simply the second polynomial.
if self.is_zero() {
return other.clone();
}

// If the second polynomial is zero, the result is simply the first polynomial.
if other.is_zero() {
return self.clone();
}

// Determine which polynomial has the higher degree.
let (longer, shorter) = if self.degree() >= other.degree() {
(self, other)
} else {
let mut result = other.clone();
result
.coeffs
.iter_mut()
.zip(&self.coeffs)
.for_each(|(a, b)| {
*a += b;
});
result
(other, self)
};

// Start with a copy of the longer polynomial as the base for the result.
let mut result = longer.clone();

// Iterate through the coefficients of the `shorter` polynomial.
// Add them to the corresponding coefficients in the `longer` polynomial.
cfg_iter_mut!(result)
.zip(&shorter.coeffs)
.for_each(|(a, b)| *a += b);

// Remove any trailing zeros from the resulting polynomial.
result.truncate_leading_zeros();

result
}
}
Expand Down
Loading