1

all. Would be grateful if someone could clarify the following.

We have a basic factorial function and a for loop with a try catch block which runs the function until error "Maximum call stack size is exceeded" is thrown.

When run in while loop max N is consistently 15699.

However when run without for loop, max call stack size is 11416.

Everything greater then 11416 number throws the "Maximum call stack size exceeded" error.

I would assume that the factorial function will be able to run with anything lesser than 15699, but it's not the case.

Please see the code and screenshots of results below. Code executed in in IDEA terminal, node -v - 14.16.1.

Would be very grateful if someone could clarify that to me. Thank you very much in advance, Katya

Max N of below is 15699

const nFactorial = (n) => {
    if (n === 1) {
        return 1;
    }
    return n * nFactorial (n - 1);
};

let n = 1;
while (n <= 100000) {
    try {
        nFactorial (n);
        n++;
    } catch (e) {
        console.log(`${e.message} with N = ${n}`);
        break;
    }
}

enter image description here

Below code only runs with N = 11416 and throws with anything greater than that number.

const nFactorial = (n) => {
    if (n === 1) {
        return 1;
    }
    return n * nFactorial (n - 1);
};

const n = 11416;
try {
    nFactorial (n);
} catch (e) {
    console.log(`${e.message} with N = ${n}`);
} 

enter image description here

  • Change the datatype to [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) – Randy Casburn Feb 02 '22 at 03:13
  • I don't think that you realize how big of a number `11416!` actually is. With this function: `const factorial = (n) => BigInt(n) ? BigInt(n) * factorial(BigInt(n) - 1n) : 1n;` The highest value for `n` I could go was 8928. And that brings back a number that is 31,398 digits long. The max safe integer in JS is 9,007,199,254,740,991, and that is only 16 digits long – Steve Feb 02 '22 at 03:54
  • Thank you for getting back to me and to pointing for the JS safe integers value. – Katya Horton Feb 02 '22 at 04:02

0 Answers0