Skip to content

Commit 94a47ee

Browse files
committed
added factorial number implementation
1 parent 5f865d8 commit 94a47ee

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Factorial.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n.
2+
3+
// For example factorial of 6 is 6*5*4*3*2*1 which is 720.
4+
5+
// Approach 1(For loop)
6+
7+
function factorialWithFoorLoop(num) {
8+
let result = 1;
9+
for (let i = num; i > 0; i--) {
10+
result *= i;
11+
}
12+
return result;
13+
}
14+
console.log(factorialWithFoorLoop(10));
15+
16+
// Approach 2(While loop)
17+
18+
function factorialWithWhileLoop(num) {
19+
let result = 1;
20+
while (num > 0) {
21+
result *= num;
22+
num--;
23+
}
24+
return result;
25+
}
26+
27+
console.log(factorialWithWhileLoop(5));
28+
29+
// Approach 3(Recursive)
30+
31+
function factorialWithRecursion(num) {
32+
if (num == 0) return 1;
33+
else return num * factorialWithRecursion(num - 1);
34+
}
35+
console.log(factorialWithRecursion(10));

0 commit comments

Comments
 (0)