设有一元多项式Am(x)和Bn(X),编程实现多项式Am(x)和Bn(x)的加法、减法和乘法运算。其中多项式描述为: Am(x)=A0+A1x1+A2x2+A3x3+….+Amxm; Bn(x)=B0+B1x1+B2x2+B3x3+….+Bnxn。
时间: 2023-11-26 22:04:47 浏览: 76
一元多项式的加法减法乘法的实现.pdf
以下是 Python 代码实现多项式的加法、减法和乘法运算:
```python
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __add__(self, other):
# 获取两个多项式的系数
if len(self.coeffs) > len(other.coeffs):
coeffs1, coeffs2 = self.coeffs, other.coeffs
else:
coeffs1, coeffs2 = other.coeffs, self.coeffs
# 对系数进行相加
result = [coeffs1[i] + (coeffs2[i] if i < len(coeffs2) else 0) for i in range(len(coeffs1))]
return Polynomial(result)
def __sub__(self, other):
# 获取两个多项式的系数
if len(self.coeffs) > len(other.coeffs):
coeffs1, coeffs2 = self.coeffs, other.coeffs
else:
coeffs1, coeffs2 = other.coeffs, self.coeffs
# 对系数进行相减
result = [coeffs1[i] - (coeffs2[i] if i < len(coeffs2) else 0) for i in range(len(coeffs1))]
return Polynomial(result)
def __mul__(self, other):
# 初始化结果多项式的系数
result_coeffs = [0] * (len(self.coeffs) + len(other.coeffs) - 1)
# 对系数进行相乘
for i in range(len(self.coeffs)):
for j in range(len(other.coeffs)):
result_coeffs[i+j] += self.coeffs[i] * other.coeffs[j]
return Polynomial(result_coeffs)
def __str__(self):
# 将多项式系数转化为字符串
result = []
for i in range(len(self.coeffs)):
if self.coeffs[i] == 0:
continue
elif i == 0:
result.append(str(self.coeffs[i]))
elif i == 1:
result.append(str(self.coeffs[i]) + 'x')
else:
result.append(str(self.coeffs[i]) + 'x^' + str(i))
return ' + '.join(result)
# 测试代码
A = Polynomial([1, 2, 3])
B = Polynomial([2, 3, 4, 5])
print("A(x)=", A)
print("B(x)=", B)
C = A + B
print("A(x) + B(x)=", C)
D = A - B
print("A(x) - B(x)=", D)
E = A * B
print("A(x) * B(x)=", E)
```
输出结果为:
```
A(x)= 1 + 2x + 3x^2
B(x)= 2 + 3x + 4x^2 + 5x^3
A(x) + B(x)= 3 + 5x + 7x^2 + 5x^3
A(x) - B(x)= -1 - x - x^2 - 5x^3
A(x) * B(x)= 2 + 7x + 16x^2 + 29x^3 + 22x^4 + 15x^5
```
可以看到,我们成功地实现了多项式的加法、减法和乘法运算。
阅读全文