使用 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

更新日期:2021 年 4 月 17 日

257 次瀏覽

開始你的職業

完成課程獲得認證

開始
廣告
© . All rights reserved.