def polynomial_long_division(dividend, divisor): # Copy the dividend so we can modify it dividend = dividend[:] result = [] while len(dividend) >= len(divisor): # Degree difference deg_diff = len(dividend) - len(divisor) # Leading coefficient of the quotient term lead_coeff = dividend[0] / divisor[0] # Construct the current term of the quotient term = [0] * deg_diff + [lead_coeff] result = poly_add(result, term) # Subtract (divisor * term) from dividend subtrahend = poly_multiply(divisor, term) dividend = poly_subtract(dividend, subtrahend) # Remove leading zeroes while dividend and abs(dividend[0]) < 1e-10: dividend.pop(0) return result, dividend # quotient, remainder def poly_add(p1, p2): # Pad the shorter list with zeros diff = len(p1) - len(p2) if diff > 0: p2 = [0]*diff + p2 elif diff < 0: p1 = [0]*(-diff) + p1 return [a + b for a, b in zip(p1, p2)] def poly_subtract(p1, p2): # Pad the shorter list with zeros diff = len(p1) - len(p2) if diff > 0: p2 = [0]*diff + p2 elif diff < 0: p1 = [0]*(-diff) + p1 return [a - b for a, b in zip(p1, p2)] def poly_multiply(p, q): result = [0] * (len(p) + len(q) - 1) for i in range(len(p)): for j in range(len(q)): result[i + j] += p[i] * q[j] return result # Example: (x^3 + 4x^2 + 18x + 17) / (x + 1) dividend = [1, 4, 18, 17] # x^3 + 4x^2 + 18x + 17 divisor = [1, 1] # x + 1 quotient, remainder = polynomial_long_division(dividend, divisor) print("Quotient:", quotient) print("Remainder:", remainder)