js实现多项式累加
实现多项式累加的方法
多项式累加可以通过多种方式实现,以下是几种常见的JavaScript实现方法:
使用数组和reduce方法
将多项式的系数存储在数组中,使用reduce方法进行累加:
function addPolynomials(poly1, poly2) {
const maxLength = Math.max(poly1.length, poly2.length);
const result = new Array(maxLength).fill(0);
for (let i = 0; i < poly1.length; i++) {
result[i] += poly1[i];
}
for (let i = 0; i < poly2.length; i++) {
result[i] += poly2[i];
}
return result;
}
// 示例:3x^2 + 2x + 1 和 4x + 5 相加
const poly1 = [1, 2, 3]; // 1 + 2x + 3x^2
const poly2 = [5, 4]; // 5 + 4x
console.log(addPolynomials(poly1, poly2)); // [6, 6, 3]
使用对象表示多项式
将多项式表示为对象,键为指数,值为系数:
function addPolynomials(poly1, poly2) {
const result = {...poly1};
for (const [exp, coeff] of Object.entries(poly2)) {
result[exp] = (result[exp] || 0) + coeff;
}
return result;
}
// 示例:3x^2 + 2x + 1 和 4x + 5 相加
const poly1 = {0: 1, 1: 2, 2: 3}; // 1 + 2x + 3x^2
const poly2 = {0: 5, 1: 4}; // 5 + 4x
console.log(addPolynomials(poly1, poly2)); // {0: 6, 1: 6, 2: 3}
处理稀疏多项式
对于稀疏多项式,可以优化存储和计算:
function addPolynomials(poly1, poly2) {
const terms = new Map();
poly1.forEach(term => terms.set(term.exp, (terms.get(term.exp) || 0) + term.coeff));
poly2.forEach(term => terms.set(term.exp, (terms.get(term.exp) || 0) + term.coeff));
return Array.from(terms.entries())
.map(([exp, coeff]) => ({exp, coeff}))
.sort((a, b) => b.exp - a.exp);
}
// 示例:3x^100 + 2x + 1 和 4x^50 + 5 相加
const poly1 = [
{exp: 0, coeff: 1},
{exp: 1, coeff: 2},
{exp: 100, coeff: 3}
];
const poly2 = [
{exp: 0, coeff: 5},
{exp: 50, coeff: 4}
];
console.log(addPolynomials(poly1, poly2));
格式化输出结果
将计算结果格式化为可读的字符串:

function polynomialToString(poly) {
return poly.reduce((str, coeff, exp) => {
if (coeff === 0) return str;
const sign = coeff >= 0 ? '+' : '-';
const absCoeff = Math.abs(coeff);
let term = '';
if (exp === 0) {
term = `${absCoeff}`;
} else {
term = absCoeff === 1 ? `x^${exp}` : `${absCoeff}x^${exp}`;
}
return `${sign} ${term} ${str}`;
}, '').trim() || '0';
}
const result = [6, 6, 3];
console.log(polynomialToString(result)); // "+ 3x^2 + 6x + 6"
这些方法可以根据实际需求选择使用,数组方法适合密集多项式,对象方法适合处理任意指数,稀疏表示适合处理高阶稀疏多项式。






