Search code examples
javascriptfactorialbigint

Factorial Digit Sum Project Euler 20


I would need some help with this code bellow.

function main(n) {
  factCounter = 1;
  for (let i = n; i > 0; --i) {
    factCounter *= i;
  }
  let numArr = BigInt(factCounter).toString().split('');
  let sum = 0;
  numArr.forEach((el) => (sum += +el));
  console.log(sum);
}
main(100);

It is solution for Project Euler #20, where i need to get the sum of all digits from 100! (factorial). But from some reason it gives me wrong answer. My output is 734, but expected output should be 648.


Solution

  • You're doing operations on floating point numbers (non bigints), then converting to a bigint at the end, which doesn't accomplish anything. If the multiplication overflows, you'll get an inaccurate number, and that inaccuracy will be maintained when converting to a bigint. Instead, use bigints the entire time:

    function main(n) {
      let factCounter = 1n;
      for (let i = n; i > 0n; --i) {
        factCounter *= i;
      }
      let numArr = factCounter.toString().split('');
      let sum = 0;
      numArr.forEach((el) => (sum += +el));
      console.log(sum);
    }
    main(100n);