Good day. It is necessary to override the multiplication operation for the class polynomial. the polynomial itself is given by an array of coefficients and can be of arbitrary length. All the time there are problems with the index out of the array. It feels like everything should be much simpler. but it doesn't get any easier. Thank you in advance

public class Polynom { public int[] coefficients; public Polynom(params int[] coefficients) { this.coefficients = coefficients; } public static Polynom operator * (Polynom polynom1, Polynom polynom2) { int size = polynom1.coefficients.Length + polynom2.coefficients.Length; int[] multiplyCoefficients = new int[size - 1]; int a = polynom1.coefficients.Length; int b = polynom2.coefficients.Length; int c = multiplyCoefficients.Length; if (a>= b) { for (int i=0; i<multiplyCoefficients.Length; i++) { if ((i >= 0) && (i < b)) for (int j = 0; j <= i; j++) { multiplyCoefficients[i] += polynom1.coefficients[j] * polynom2.coefficients[i - j]; } if ((i >= b) && (i < a)) for (int j = b; j <= i; j++) { multiplyCoefficients[i] += polynom1.coefficients[j] * polynom2.coefficients[i - j]; } if ((i >= a) && (i < c)) for (int j = a; j <= i; j++) { multiplyCoefficients[i] += polynom1.coefficients[j] * polynom2.coefficients[i - j]; } } } return new Polynom(multiplyCoefficients); } } 
  • Wow, a whole bunch of cycles and branching ... - Andrew NOP

1 answer 1

By multiplying the higher terms, we get a term of degree n1 + n2 , where n1 and n2 are the degrees of the polynomial multipliers. Taking into account the presence of a free term (with degree 0) we need (n1 - 1) + (n2 - 1) + 1 = n1 + n2 - 1 cells.

We use the fact that when creating an array int[] it will be initialized with zeros. Now we just need to multiply everything by term and accumulate the sums of these products in the corresponding cells of the array. Here it is clear that when multiplying members with powers of i and j , a term of degree i + j obtained. Total it turns out such a simple concise code:

 public static Polynom operator *(Polynom polynom1, Polynom polynom2) { int[] coeffs = new int[polynom1.coefficients.Length + polynom2.coefficients.Length - 1]; for (int i = 0; i < polynom1.coefficients.Length; ++i) for (int j = 0; j < polynom2.coefficients.Length; ++j) coeffs[i + j] += polynom1.coefficients[i] * polynom2.coefficients[j]; return new Polynom(coeffs); } 

Example of use:

 var p1 = new Polynom(1, 2, 3); var p2 = new Polynom(2, 3, 4); var p3 = p1 * p2; Console.WriteLine(p1); Console.WriteLine(p2); Console.WriteLine(p3); 

Conclusion:

 3x^2+2x+1 4x^2+3x+2 12x^4+17x^3+16x^2+7x+2 
  • really, very beautiful and concise solution. thanks a lot!! - Fiorie