Skip to content

Commit e608780

Browse files
committed
function to calculate factorial in JavaScript
1 parent 5717b57 commit e608780

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

factorial.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Challenge
2+
// 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.
3+
// Sample Test Cases
4+
// Input:4
5+
// Output:24
6+
7+
// Input:8
8+
// Output:40320
9+
10+
//========================================================//
11+
12+
//========================================================//
13+
14+
//========================================================//
15+
16+
//1st method.
17+
function factorial(num) {
18+
19+
var facto = 1;
20+
21+
for (var i = 1; i <= num; i++) {
22+
// multiply each number between 1 and num
23+
// factorial = 1 * 1 = 1
24+
// factorial = 1 * 2 = 2
25+
// factorial = 2 * 3 = 6
26+
// factorial = 6 * 4 = 24
27+
// ...
28+
facto = facto * i;
29+
}
30+
31+
return factorial;
32+
33+
}
34+
35+
factorial(4);
36+
factorial(10);
37+
factorial(9);
38+
factorial(5);
39+
//========================================================//
40+
41+
//========================================================//
42+
43+
//========================================================//
44+
45+
// 2nd Method
46+
function factorial(num) {
47+
48+
// our factorial function
49+
function facto(n) {
50+
51+
// terminate the recursion once we hit zero
52+
if (n===0) {
53+
return 1;
54+
}
55+
56+
// otherwise keep calling the function recursively
57+
else {
58+
return facto(n-1) * n;
59+
}
60+
61+
}
62+
63+
return facto(num);
64+
65+
}
66+
67+
factorial(4);
68+

0 commit comments

Comments
 (0)