simple-statistics
Version:
37 lines (33 loc) • 1.3 kB
JavaScript
/**
* A [Factorial](https://en.wikipedia.org/wiki/Factorial), usually written n!, is the product of all positive
* integers less than or equal to n. Often factorial is implemented
* recursively, but this iterative approach is significantly faster
* and simpler.
*
* @param {number} n input, must be an integer number 1 or greater
* @returns {number} factorial: n!
* @throws {Error} if n is less than 0 or not an integer
* @example
* factorial(5); // => 120
*/
function factorial(n) {
// factorial is mathematically undefined for negative numbers
if (n < 0) {
throw new Error("factorial requires a non-negative value");
}
if (Math.floor(n) !== n) {
throw new Error("factorial requires an integer input");
}
// typically you'll expand the factorial function going down, like
// 5! = 5 * 4 * 3 * 2 * 1. This is going in the opposite direction,
// counting from 2 up to the number in question, and since anything
// multiplied by 1 is itself, the loop only needs to start at 2.
let accumulator = 1;
for (let i = 2; i <= n; i++) {
// for each number up to and including the number `n`, multiply
// the accumulator my that number.
accumulator *= i;
}
return accumulator;
}
export default factorial;