1

I think that this code works but in the challenge they asking me to return "15511210043330985984000000" instead of "1.5511210043330984e+25" I don't understand what could be the problem. I've tried putting "BigInt" before my result but that gives me something like "15511210043330985984000000n" this "n" at the end of every number.

function extraLongFactorials(n) {
  let result = 1;
  for(let i = n; i >= 1; i--) {
    result *= i;
  }
  return result;
}

console.log(extraLongFactorials(25));

// should be 15511210043330985984000000
Chris
  • 162
  • 1
  • 11
  • Does this answer your question? [How to avoid scientific notation for large numbers in JavaScript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) – Randy Casburn Mar 31 '21 at 22:08
  • At some point you will have to reconcile that 1) The only way to produce the output without either scientific notation or the `n` on the BigInt is to us BigInt (your intuition is correct) but you have to call `.toString()` on the BigInt to get the output you desire; 2) JavaScript truncates the zeros at the end of the number. 3) be careful not to inadvertently round the number when creating the BigInt. – Randy Casburn Mar 31 '21 at 22:14

3 Answers3

1

Well, I found this solution. It is quite close to what @undg was saying but a little different that is the answer I was expecting.

function extraLongFactorials(n) {
  n = BigInt(n)
  let result = BigInt(1);
  
  
  for(let i = n; i >= 1; i--) {
    result *= i;
  }
  return result.toString();
}

console.log(extraLongFactorials(25)); // 15511210043330985984000000
Chris
  • 162
  • 1
  • 11
0

Use BigInt() followed by toString()

BigInt(Number.MAX_VALUE).toString()
//'179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368'
undg
  • 708
  • 3
  • 14
  • I used "BigInt() followed by toString()" it works but that did not give me the answer I expected "15511210043330983907819520" – Chris Apr 01 '21 at 00:17
0

Javascript recursive solution

function extraLongFactorials(n) {
  const factorial = (int) => {
    const bigInt = BigInt(int)
    return bigInt === 0n ? 1n : bigInt * factorial(bigInt - 1n)
  }
  console.log(factorial(n).toString())
}
extraLongFactorials(25)