Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Using BigInt to calculate long factorials in JavaScript
In JavaScript, calculating factorials of large numbers requires the BigInt data type to avoid precision loss. BigInt handles arbitrarily large integers, making it perfect for computing long factorials that exceed JavaScript's standard number limits.
What is BigInt?
BigInt is a built-in JavaScript data type introduced in ECMAScript 2020 that represents integers of arbitrary size. Unlike the standard Number type, which has a maximum safe integer limit of 2^53 - 1, BigInt can handle infinitely large integers.
// Regular numbers have limits console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 // BigInt can handle much larger values console.log(BigInt(Number.MAX_SAFE_INTEGER) * 100n);
9007199254740991 900719925474099100
The Factorial Problem
Factorial (n!) is the product of all positive integers up to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. Large factorials grow extremely quickly and exceed JavaScript's number precision.
// Problem with regular numbers for large factorials
function regularFactorial(n) {
let result = 1;
for (let i = 2; i
25! with regular numbers: 15511210043330985000000
BigInt Factorial Solution
Using BigInt ensures accurate calculation of large factorials without precision loss:
function calculateBigIntFactorial(n) {
// Convert input to BigInt
const num = BigInt(n);
let result = 1n; // BigInt literal notation
// Loop from 2 to n using BigInt
for (let i = 2n; i
5! = 120n
25! = 15511210043330985984000000n
50! = 30414093201713378043612608166064768844377641568960512000000000000n
Comparison: Number vs BigInt
| Aspect | Number | BigInt |
|---|---|---|
| Maximum Value | 2^53 - 1 | No limit |
| Precision | Limited for large values | Always accurate |
| Performance | Faster | Slightly slower |
| Syntax | 25 | 25n or BigInt(25) |
Practical Example: Very Large Factorial
function factorialWithValidation(n) {
if (n
100! has 158 digits
First 50 chars: 93326215443944152681699238856266700490715968264...
Performance Considerations
The time complexity is O(n) as we iterate from 2 to n once. Space complexity is O(1) since we only store the current result. While BigInt operations are slightly slower than regular number operations, the accuracy gained is essential for large factorial calculations.
Conclusion
BigInt enables accurate calculation of large factorials in JavaScript without precision loss. This approach is essential when working with mathematical computations involving very large numbers where accuracy is critical.
