使用 JavaScript 展开二项式表达式
问题
我们需要编写一个 JavaScript 函数,该函数接受一个形式为 (ax+b)^n 的表达式,其中 a 和 b 是正整数或负整数,x 是任何单字符变量,n 是自然数。如果 a = 1,则不会在变量前面放置系数。
我们的函数应返回以下形式的展开式字符串:ax^b+cx^d+ex^f...,其中 a、c 和 e 是项的系数,x 是在原始表达式中传递的原始单字符变量,以及 b、d 和 f 是 x 在每项中被提升的幂,并按降序排列
示例
以下是代码 -
const str = '(8a+6)^4';
const trim = value => value === 1 ? '' : value === -1 ? '-' : value
const factorial = (value, total = 1) =>
value <= 1 ? total : factorial(value - 1, total * value)
const find = (str = '') => {
let [op1, coefficient, variable, op2, constant, power] = str
.match(/(\W)(\d*)(\w)(\W)(\d+)..(\d+)/)
.slice(1)
power = +power
if (!power) {
return '1'
}
if (power === 1) {
return str.match(/\((.*)\)/)[1]
}
coefficient =
op1 === '-'
? coefficient
? -coefficient
: -1
: coefficient
? +coefficient
: 1
constant = op2 === '-' ? -constant : +constant
const factorials = Array.from({ length: power + 1 }, (_,i) => factorial(i))
let result = ''
for (let i = 0, p = power; i <= power; ++i, p = power - i) {
let judge =
factorials[power] / (factorials[i] * factorials[p]) *
(coefficient * p * constant * i)
if (!judge) {
continue
}
result += p
? trim(judge) + variable + (p === 1 ? '' : `^${p}`)
: judge
result += '+'
}
return result.replace(/\+\-/g, '-').replace(/\+$/, '')
};
console.log(find(str));输出
576a^3+1152a^2+576a
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP