russiandobby
russiandobby

Reputation: 79

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

I am doing euler problem where you need to find the sum of integers of a factorial number. so for example 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. I wrote this using big-int library to deal with large numbers.

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;
}

this works for small factorials and gives right answers but as soon as you go for something bigger then 12 it gives wrong answers, for example for 100 I get 683 but the answer according to the site should be 648 ><. I am guessing the big int library i am using returns wrong number but it worked for smaller numbers so I don't see what the issue can be.

Upvotes: 0

Views: 167

Answers (2)

blex
blex

Reputation: 25659

Additionally to Jeril's answer which is your curlpit, you can also use reduce to calculate the sum of an Array. Demo:

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>

Upvotes: 0

Jeril Sebastian
Jeril Sebastian

Reputation: 853

I'm assuming the BigInt library you are using takes a big number as a string. Something like

bigint("23837458934509644434537504952635462348")

You are doing

let result = bigInt(factorialize(x));

The call to factorialize(100) has already overflowed Javascript's MAX_SAFE_INTEGER and passes the wrong string to the bigInt call.

You have to use BigInts to calculate the factorial as well.

Upvotes: 4

Related Questions