js实现多项式累加
实现多项式累加的方法
多项式累加可以通过多种方式实现,以下是几种常见的方法:
使用数组存储系数并累加
将多项式的系数存储在数组中,数组的索引对应变量的幂次。例如,多项式 $3x^2 + 2x + 1$ 可以表示为 [1, 2, 3]。

function addPolynomials(poly1, poly2) {
const maxLength = Math.max(poly1.length, poly2.length);
const result = [];
for (let i = 0; i < maxLength; i++) {
const coeff1 = poly1[i] || 0;
const coeff2 = poly2[i] || 0;
result.push(coeff1 + coeff2);
}
return result;
}
// 示例:计算 (3x^2 + 2x + 1) + (x^2 + 4x + 5)
const poly1 = [1, 2, 3];
const poly2 = [5, 4, 1];
console.log(addPolynomials(poly1, poly2)); // 输出 [6, 6, 4]
使用对象存储幂次和系数
如果多项式的幂次较高且稀疏,可以使用对象来存储幂次和系数的键值对。

function addPolynomials(poly1, poly2) {
const result = {};
// 累加第一个多项式的系数
for (const power in poly1) {
result[power] = (result[power] || 0) + poly1[power];
}
// 累加第二个多项式的系数
for (const power in poly2) {
result[power] = (result[power] || 0) + poly2[power];
}
return result;
}
// 示例:计算 (3x^2 + 2x + 1) + (x^2 + 4x + 5)
const poly1 = { 0: 1, 1: 2, 2: 3 };
const poly2 = { 0: 5, 1: 4, 2: 1 };
console.log(addPolynomials(poly1, poly2)); // 输出 { 0: 6, 1: 6, 2: 4 }
处理多项式字符串输入
如果输入是多项式字符串(如 "3x^2 + 2x + 1"),可以先将字符串解析为系数数组或对象,再进行累加。
function parsePolynomial(str) {
const terms = str.split(/\s*\+\s*/);
const poly = {};
terms.forEach(term => {
const match = term.match(/(\d*)x\^?(\d*)|(\d+)/);
let coeff, power;
if (match[3]) {
// 常数项
coeff = parseInt(match[3], 10);
power = 0;
} else {
// 含x的项
coeff = match[1] === '' ? 1 : parseInt(match[1], 10);
power = match[2] === '' ? 1 : parseInt(match[2], 10);
}
poly[power] = (poly[power] || 0) + coeff;
});
return poly;
}
function addPolynomials(poly1, poly2) {
const result = {};
for (const power in poly1) {
result[power] = (result[power] || 0) + poly1[power];
}
for (const power in poly2) {
result[power] = (result[power] || 0) + poly2[power];
}
return result;
}
// 示例:计算 (3x^2 + 2x + 1) + (x^2 + 4x + 5)
const poly1 = parsePolynomial("3x^2 + 2x + 1");
const poly2 = parsePolynomial("x^2 + 4x + 5");
console.log(addPolynomials(poly1, poly2)); // 输出 { 0: 6, 1: 6, 2: 4 }
注意事项
- 输入的多项式可以是数组、对象或字符串形式,需根据实际需求选择解析方式。
- 稀疏多项式(某些幂次系数为0)适合用对象存储,而密集多项式适合用数组存储。
- 对于更高阶的多项式操作(如乘法、求导等),可以基于累加方法进一步扩展实现。






