forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Factorial.js
37 lines (30 loc) · 879 Bytes
/
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
/*
author: PatOnTheBack
license: GPL-3.0 or later
Modified from:
https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_python.py
This script will find the factorial of a number provided by the user.
More about factorials:
https://en.wikipedia.org/wiki/factorial
*/
'use strict'
const calcRange = (num) => {
return [...Array(num).keys()].map(i => i + 1)
}
const calcFactorial = (num) => {
if (num === 0) {
return 'The factorial of 0 is 1.'
}
if (num < 0) {
return 'Sorry, factorial does not exist for negative numbers.'
}
if (!num) {
return 'Sorry, factorial does not exist for null or undefined numbers.'
}
if (num > 0) {
const range = calcRange(num)
const factorial = range.reduce((a, c) => a * c, 1)
return `The factorial of ${num} is ${factorial}`
}
}
export { calcFactorial }