尝试使用 big-int npm 求阶乘数之和给出了错误的答案

Trying to find sum of factorial number using big-int npm gives wrong answer

我正在做欧拉问题,您需要找到阶乘数的整数和。例如 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 ><。我猜我使用的是大 int 库 returns 错误的数字,但它适用于较小的数字,所以我看不出问题所在。

我假设您使用的 BigInt 库将大数字作为字符串。像

bigint("23837458934509644434537504952635462348")

你在做

let result = bigInt(factorialize(x));

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

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

除了 Jeril 的答案是你的 currpit,你还可以使用 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
<script src="https://peterolson.github.io/BigInteger.js/BigInteger.min.js"></script>