尝试使用big-int npm查找阶乘数之和给出错误答案

问题描述 投票:0回答:2

我正在做欧拉问题,您需要找到阶乘数的整数和。例如10!是3 + 6 + 2 + 8 + 8 + 0 + 0 = 27。我使用big-int库编写此代码来处理大量数字。

factorialize =(num)=> {
  if (num < 0) {
        return -1;
  }
  else if (num == 0) {
      return 1;
  }
  else {
      return (num * factorialize(num - 1));
  }
}


findFactorialSum=(x)=>{
  let total=0;
  let result = bigInt(factorialize(x));
  // let result=factorialize(x).toString().split("").map(el => parseInt(el));
  // result.split("");
  let converted = result.toString().split("").map(el => parseInt(el));
  console.log(converted);
  for(let i=0;i<=converted.length-1;i++)
{
  total=total+converted[i]
}  
  console.log(total);
  return total;
}

这适用于较小的阶乘并且给出正确的答案,但是一旦您选择更大的东西然后给出12,就会给出错误的答案,例如,对于100,我得到683,但根据站点的答案应该为648>

javascript biginteger
2个回答
2
投票

我假设您正在使用的BigInt库采用一个大数字作为字符串。有点像

bigint("23837458934509644434537504952635462348")

您正在做

let result = bigInt(factorialize(x));

factorialize(100)的调用已溢出Javascript的MAX_SAFE_INTEGER,并将错误的字符串传递给bigInt调用。

您还必须使用BigInts来计算阶乘。


0
投票

除了Jeril回答的问题之外,您还可以使用reduce计算数组的总和。演示:

reduce
const factorialize = (bigNum) => {
  if (bigNum.lt(0)) {
    return bigInt(-1);
  } else if (bigNum.eq(0)) {
    return bigInt(1);
  } else {
    return bigNum.times(factorialize(bigNum.minus(1)));
  }
};


const findFactorialSum = (x) => {
  const result = factorialize(bigInt(x)),
        total = result.toString().split('')
                      .reduce((sum, digit) => sum + +digit, 0);

  console.log(result.toString().split('').join('+') + ' = ' + total);
  return total;
};

findFactorialSum(10); // 27
findFactorialSum(15); // 45
findFactorialSum(20); // 54
© www.soinside.com 2019 - 2024. All rights reserved.