JavaScript Factorial

By Xah Lee. Date: .

Here's a function to compute factiorial, with memorization feature.

/* [
xah_factorial(n) returns the factorial of n.
http://xahlee.info/js/js_factorial.html
version 2020-07-17
] */

const xah_factorial_values = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000];

const xah_factorial = ((n) => ( ( n < xah_factorial_values.length ) ? (xah_factorial_values[n])
: (xah_factorial_values[n] = xah_factorial(n-1) * n) ) );

// test
console.log( xah_factorial(20) === 2432902008176640000 ); // true

Binomial formula

Here's function to compute binomial coefficient.

// xah_binomial(n,k) returns the Binomial coefficient. (or, the possibilities of n things take k) Version 2020-07-17
const xah_binomial = ((n,k) => xah_factorial(n) / ( xah_factorial(k) * xah_factorial(n - k) ) );
JS in Depth
XAH
Buy Xah JavaScript Tutorial