超超超超超大数字相乘计算

function multiply(a, b) {
  a = a.split('').reverse()
  b = b.split('').reverse()

  let _tenMark = 0, _sumArr = [], _conArr = [], _sum = []
  for (let i = 0, j = b.length; i < j; i++) {
    if (i > 0) _conArr.push(0)
    for (let m = 0, n = a.length; m < n; m++) {
      if (_sumArr.length === i) {
        _sumArr.push([])
        _sumArr[i] = _sumArr[i].concat(_conArr)
      }

      let _result = Number(a[m] * b[i] + _tenMark)
      let _single = _result % 10
      if (m === n - 1) {
        _tenMark = 0
        _sumArr[i] = _sumArr[i].concat(_result.toString(10).split('').reverse())
      }
      else {
        _tenMark = Math.floor(_result / 10)
        _sumArr[i].push(_single)
      }
    }
  }

  _tenMark = 0
  for (let i = 0, j = _sumArr[_sumArr.length - 1].length; i < j; i++) {
    let _result = 0, _single = 0
    for (let m = 0, n = _sumArr.length; m < n; m++) {
      _result += !!Number(_sumArr[m][i]) ? Number(_sumArr[m][i]) : 0
    }
    _result += _tenMark
    _single = _result % 10
    if (i === j - 1) {
      _sum = _sum.concat(_result.toString(10).split('').reverse())
    }
    else {
      _sum.push(_single)
      _tenMark = Math.floor(_result / 10)

    }
  }

  _sum = _sum.reverse().join('').replace(/\b(0+)/gi, "")

  return _sum ? _sum : '0'
}

console.log(multiply('1020303004875647366210', '2774537626200857473632627613')) // 2830869077153280552556547081187254342445169156730
展开阅读全文

没有更多推荐了,返回首页