Skip to content

Commit

Permalink
moved from memoization to dp implementation of factorials
Browse files Browse the repository at this point in the history
  • Loading branch information
CristianDavideConte committed Feb 29, 2024
1 parent 7acecb2 commit b3fde04
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions src/main/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,35 @@
* An array containing the currently calculated factorials.
*
* Note that given an index i, `factorials[i] contains i!`.
* E.g.
* e.g.
* - factorials[0] = 0! = 1
* - factorials[5] = 5! = 120
* - ...
*/
const _factorials = [
1, 1, 2, 6, 24, 120, //0!..5!
720, 5040, 40320, 362880, 3628800, //6!..10!
39916800, 479001600, 6227020800, 87178291200, 1307674368000, //11!..15!
20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000 //16!..20!
];
const _factorials = new Array(170);

/**
* Returns the factorial of `value`. If `value > 170`, `Infinity` is returned.
* Returns the factorial of `value`.
* If `value > 170`, `Infinity` is returned.
*
* Note that `no type checks` are done on `value`.
* @param {number} value The number to calculate the factorial of.
* @returns {number} The factorial of `value`.
*/
export const FACTORIAL = (value) => {
let _fact = _factorials[value];
if (_factorials[value]) return _factorials[value];
if (value > 170) return Infinity;
if (value == 0) return 1;

if (!_fact) {
_fact = value * FACTORIAL(value - 1);
_factorials[value] = _fact;
let _fact = 1;
for (let i = 1; i <= value; i++) {
_fact *= i;
_factorials[i] = _fact;
}

return _fact;
}
FACTORIAL(170); //Forcefully cache the factorials
Object.seal(_factorials);

/**
* Checks whether `value` is a positive number (i.e. > 0).
Expand Down

0 comments on commit b3fde04

Please sign in to comment.