def add(self, other: 'Polynomial') -> 'Polynomial': if (self.is_zero): return other if (other.is_zero): return self # Assume this polynomial is smaller than the other one smaller = self.coefficients larger = other.coefficients # Assumption is wrong. exchange the two arrays if (len(smaller) > len(larger)): smaller = other.coefficients larger = self.coefficients result = list([0] * len(larger)) delta = len(larger) - len(smaller) # Copy high-order terms only found in higher-degree polynomial's coefficients # Array.Copy(Larger, 0, Result, 0, Delta); for i in range(len(larger)): result[i] = larger[i] # Add the coefficients of the two polynomials # for(int Index = Delta; Index < Larger.Length; Index++) for i in range(delta, len(larger)): # Result[Index] = Modulus.Add(Smaller[Index - Delta], Larger[Index]); result[i] = Modulus.add(smaller[i - delta], larger[i]) return Polynomial(0, 0, result)
def evaluate_at(self, x) -> int: """ Evaluation of this polynomial at a given point """ if (x == 0): return self.coefficients[0] result = 0 # Return the x^1 coefficient if (x == 1): # Return the sum of the coefficients for coefficient in self.coefficients: result = Modulus.add(result, coefficient) else: result = self.coefficients[0] for i in range (1, self.length): multiply_result = Modulus.multiply(x, result) add_result = Modulus.add(multiply_result, self.coefficients[i]) result = add_result return result
def multiply(self, other: 'Polynomial') -> 'Polynomial': """ Multiply two polynomials """ if (self.is_zero or other.is_zero): return ZERO result = list([0] * (self.length + other.length - 1)) for i in range(self.length): coeff = self.coefficients[i] for j in range(other.length): result[i+j] = Modulus.add(result[i+j], Modulus.multiply(coeff, other.coefficients[j])) return Polynomial(0, 0, result)