-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfactorial.js
89 lines (63 loc) · 1.91 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Challenge
// Using the JavaScript language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (e.g. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18 and the input will always be an integer.
// Sample Test Cases
// Input:4
// Output:24
// Input:8
// Output:40320
//========================================================//
//========================================================//
//========================================================//
//1st method.
function factorial(num) {
var facto = 1;
for (var i = 1; i <= num; i++) {
// multiply each number between 1 and num
// factorial = 1 * 1 = 1
// factorial = 1 * 2 = 2
// factorial = 2 * 3 = 6
// factorial = 6 * 4 = 24
// ...
facto = facto * i;
}
return factorial;
}
factorial(4);
factorial(10);
factorial(9);
factorial(5);
//========================================================//
//========================================================//
//========================================================//
// 2nd Method
function factorial(num) {
// our factorial function
function facto(n) {
// terminate the recursion once we hit zero
if (n===0) {
return 1;
}
// otherwise keep calling the function recursively
else {
return facto(n-1) * n;
}
}
return facto(num);
}
factorial(4);
//========================================================//
//========================================================//
//========================================================//
// 3rd Method
function FirstFactorial(num) {
if (num === 0 || num === 1) {
return 1;
}
else {
return num * FirstFactorial(num - 1);
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
FirstFactorial(10);
FirstFactorial(9);