deno.land / x / simplestatistic@v7.7.1 / src / factorial.js

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/** * 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;
simplestatistic

Version Info

Tagged at
2 years ago