/** * Polynomial multiplication * * @param a First polynomial to be multiplied. * @param b Second polynomial to be multiplied. * @return New polynomial as the product of polynomial a and polynomial b. */ // Example: The product of polynomial 2x0 + 3x1 and polynomial 1x2 + 1x3 should be 2x2 + 5x3 + 3x4 // 2x⁰ + 3x¹ X 1x² + 1x³ = 2x² + 5x³ + 3x⁴ // 2x⁰ + 3x¹ // 1x² + 1x³ // MULTIPLY // (2x⁰ * 1x²) + (2x⁰ * 1x³) + (3x¹ * 1x²) + (3x¹ * 1x³) // polyA.term0 * polyB.term0 = 2x⁰ * 1x² // polyA.term0 * polyB.term1 = 2x⁰ * 1x³ // polyA.term1 * polyB.term0 = 3x¹ * 1x² // polyA.term1 * polyB.term1 = 3x¹ * 1x³ // 2x² + 5x³ + 3x⁴ public static Polynomial Multiply(Polynomial a, Polynomial b) { // DO_NOT_EDIT_ANYTHING_ABOVE_THIS_LINE V var degreeA = a.Degree(); var degreeB = b.Degree(); var degree = degreeA + degreeB; var coefficients = new int[degree + 1]; var powers = new int[degree + 1]; var termA = a.Head; // 2x⁰ while (termA != null) { var termB = b.Head; // 1x² while (termB != null) { // termA * termB => 2x⁰ * 1x² var coefficientA = termA.Coefficient; var coefficientB = termB.Coefficient; var coefficientTotal = coefficientA * coefficientB; coefficients[termA.Power + termB.Power] += coefficientTotal; powers[termA.Power + termB.Power] = termA.Power + termB.Power; termB = termB.Next; } termA = termA.Next; } while (termA != null) { var termB = b.Head; // 1x² while (termB != null) { // termA * termB => 2x⁰ * 1x² var coefficientA = termA.Coefficient; var coefficientB = termB.Coefficient; var coefficientTotal = coefficientA * coefficientB; coefficients[termA.Power + termB.Power] += coefficientTotal; powers[termA.Power + termB.Power] = termA.Power + termB.Power; termB = termB.Next; } termA = termA.Next; } return(new Polynomial(coefficients, powers)); // DO_NOT_EDIT_ANYTHING_BELOW_THIS_LINE A }
/** * Polynomial addition * * @param a First polynomial to be added. * @param b Second polynomial to be added. * @return New polynomial as the sum of polynomial a and polynomial b. */ // Example: The result of addition of polynomial 2x0 + 0x1 + 3x2 and polynomial 0x0 + 1x1 + 0x2 should be 2x0 + 1x1 + 3x2 public static Polynomial Add(Polynomial a, Polynomial b) { // DO_NOT_EDIT_ANYTHING_ABOVE_THIS_LINE V // TODO: for loops (i) unnecessary? var degreeA = a.Degree(); var degreeB = b.Degree(); var degree = degreeA > degreeB ? degreeA : degreeB; var coefficients = new int[degree + 1]; var powers = new int[degree + 1]; var term = a.Head; while (term != null) { for (var i = 0; i <= degree; i++) { if (term.Power == i) { coefficients[i] = term.Coefficient; powers[i] = term.Power; term = term.Next; break; } } } term = b.Head; while (term != null) { for (var i = 0; i <= degree; i++) { if (term.Power == i) { coefficients[i] += term.Coefficient; term = term.Next; break; } } } return(new Polynomial(coefficients, powers)); // DO_NOT_EDIT_ANYTHING_BELOW_THIS_LINE A }