【问题标题】:Trying to find sum of factorial number using big-int npm gives wrong answer尝试使用 big-int npm 查找阶乘数的总和给出错误答案
【发布时间】:2020-05-25 20:39:10
【问题描述】:

我正在做欧拉问题,你需要找到一个阶乘数的整数之和。所以例如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


    【解决方案1】:

    我假设您使用的 BigInt 库将大数字作为字符串。类似的东西

    bigint("23837458934509644434537504952635462348")
    

    你在做

    let result = bigInt(factorialize(x));
    

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

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

    【讨论】:

      【解决方案2】:

      除了 Jeril 的 curlpit 答案之外,您还可以使用 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
      &lt;script src="https://peterolson.github.io/BigInteger.js/BigInteger.min.js"&gt;&lt;/script&gt;

      【讨论】:

        猜你喜欢
        • 2023-01-30
        • 1970-01-01
        • 1970-01-01
        • 2014-11-19
        • 2016-12-28
        • 2018-09-21
        • 2020-09-03
        • 1970-01-01
        • 2019-01-29
        相关资源
        最近更新 更多