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/
1 Answer 1
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:
BigInt
can use all the same types of simple arithmetic asNumber
, along with 0 being consideredfalsy
as usual
1n + 3n === 4n // true!
BigInt
is also usable as a JS primitive. Neat!
typeof 1n === "bigint" // true!
BigInt
andNumber
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
If the article still holds true,
BigInt
doesn't have the luxury of using operations in the built-inMath
object. So you would either need to stick to simple arithmetic, or build (or otherwise find) those implementations yourself.Since the supported operations on
BigInt
are not constant time (according to the article), it is recommended to useBigInt
strictly when a use case will frequently involve numbers higher than the largest representable int inNumber
(253). Your question is one such case, since factorials grow extremely fast, so I think it's fine as is.