public function add(Polynomial $polynomial) : Polynomial
{
// Calculate the degree of the sum of the polynomials
$sumDegree = max($this->degree, $polynomial->degree);
// Reverse the coefficients arrays so you can sum component-wise
$coefficientsA = array_reverse($this->coefficients);
$coefficientsB = array_reverse($polynomial->coefficients);
// Start with an array of coefficients that all equal 0
$sumCoefficients = array_fill(0, $sumDegree + 1, 0);
// Iterate through each degree. Get coefficients by summing component-wise.
for ($i = 0; $i < $sumDegree + 1; $i++) {
// Calculate the degree of the current sum
$degree = $sumDegree - $i;
// Get the coefficient of the i-th degree term from each polynomial if it exists, otherwise use 0
$a = $coefficientsA[$i] ?? 0;
$b = $coefficientsB[$i] ?? 0;
// The new coefficient is the sum of the original coefficients
$sumCoefficients[$degree] = $sumCoefficients[$degree] + $a + $b;
}
return new Polynomial($sumCoefficients);
}