2
\$\begingroup\$

Is there anything missing or any pitfall when using BigInt?

// Assuming n is an integer and is 0 or greater
function factorial(n) {
    var i, result = BigInt(1);

    for (i = BigInt(2); i <= n; i++) {
        result *= i;
    }
    return result;
}

console.log(factorial(69));
console.log(factorial(200));

console.log(factorial(69n));
console.log(factorial(200n));

jsfiddle: https://jsfiddle.net/adr49tz2/

\$\endgroup\$
2
\$\begingroup\$

My answer is pretty heavily based on this resource on BigInt, so feel free to explore that a bit first.

With that said, here are some of the key points I saw:

  1. BigInt can use all the same types of simple arithmetic as Number, along with 0 being considered falsy as usual
1n + 3n === 4n // true!
  1. BigInt is also usable as a JS primitive. Neat!
typeof 1n === "bigint" // true!
  1. BigInt and Number should not be mixed and matched. The coercion between the two is ambiguous, and as such JavaScript would throw an exception in that circumstance, so you should only either use one or the other.
1 + 1n // whoops
  1. If the article still holds true, BigInt doesn't have the luxury of using operations in the built-in Math object. So you would either need to stick to simple arithmetic, or build (or otherwise find) those implementations yourself.

  2. Since the supported operations on BigInt are not constant time (according to the article), it is recommended to use BigInt strictly when a use case will frequently involve numbers higher than the largest representable int in Number (253). Your question is one such case, since factorials grow extremely fast, so I think it's fine as is.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.