Skip to content

Commit df47f74

Browse files
tcoratgerPratyush
andauthored
refactor DensePolynomial add (#905)
* refactor DensePolynomial add * Use parallel iteration --------- Co-authored-by: Pratyush Mishra <pratyushmishra@berkeley.edu> Co-authored-by: Pratyush Mishra <pratyush795@gmail.com>
1 parent 104444d commit df47f74

File tree

1 file changed

+26
-23
lines changed

1 file changed

+26
-23
lines changed

poly/src/polynomial/univariate/dense.rs

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -284,32 +284,35 @@ impl<'a, F: Field> Add<&'a DensePolynomial<F>> for &DensePolynomial<F> {
284284
type Output = DensePolynomial<F>;
285285

286286
fn add(self, other: &'a DensePolynomial<F>) -> DensePolynomial<F> {
287-
let mut result = if self.is_zero() {
288-
other.clone()
289-
} else if other.is_zero() {
290-
self.clone()
291-
} else if self.degree() >= other.degree() {
292-
let mut result = self.clone();
293-
result
294-
.coeffs
295-
.iter_mut()
296-
.zip(&other.coeffs)
297-
.for_each(|(a, b)| {
298-
*a += b;
299-
});
300-
result
287+
// If the first polynomial is zero, the result is simply the second polynomial.
288+
if self.is_zero() {
289+
return other.clone();
290+
}
291+
292+
// If the second polynomial is zero, the result is simply the first polynomial.
293+
if other.is_zero() {
294+
return self.clone();
295+
}
296+
297+
// Determine which polynomial has the higher degree.
298+
let (longer, shorter) = if self.degree() >= other.degree() {
299+
(self, other)
301300
} else {
302-
let mut result = other.clone();
303-
result
304-
.coeffs
305-
.iter_mut()
306-
.zip(&self.coeffs)
307-
.for_each(|(a, b)| {
308-
*a += b;
309-
});
310-
result
301+
(other, self)
311302
};
303+
304+
// Start with a copy of the longer polynomial as the base for the result.
305+
let mut result = longer.clone();
306+
307+
// Iterate through the coefficients of the `shorter` polynomial.
308+
// Add them to the corresponding coefficients in the `longer` polynomial.
309+
cfg_iter_mut!(result)
310+
.zip(&shorter.coeffs)
311+
.for_each(|(a, b)| *a += b);
312+
313+
// Remove any trailing zeros from the resulting polynomial.
312314
result.truncate_leading_zeros();
315+
313316
result
314317
}
315318
}

0 commit comments

Comments
 (0)