Using BigInt to calculate long factorials in JavaScript



We are required to write a JavaScript function that takes in a number as the only input. The function should calculate the factorial of big numbers (greater than 10) whose factorial can be accommodated in the simple let or type variables using the new bigInt variable of JavaScript. Lastly the function should convert the factorial to a string and return the string.

For example − If the input is −

const num = 45;

Then the output should be −

const output = '119622220865480194561963161495657715064383733760000000000';

Example

The code for this will be −

const num = 45;
const longFactorial = (num) => {
   var bigInt = BigInt(num);
   var factorial = 1n;
   for (let i = 0n; i < bigInt ; i++) {
      factorial *= bigInt − i;
   }
   return String(factorial);
}
console.log(longFactorial(45));

Output

And the output in the console will be −

119622220865480194561963161495657715064383733760000000000

Advertisements