Skip to content

Commit 0b1aaf1

Browse files
committed
factorial.js
1 parent 3d495a5 commit 0b1aaf1

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// 5. Factorial of a Number
2+
3+
function factorial(n) {
4+
let fact = 1;
5+
if (n === 0) return 1;
6+
if (n === 1) return 1;
7+
8+
for (let i = 2; i <= n; i++) {
9+
fact *= i;
10+
}
11+
12+
return fact;
13+
}
14+
15+
console.log(factorial(3));
16+
console.log(factorial(1));
17+
18+
// using recursio
19+
20+
function factorials(n) {
21+
if (n === 0 || n === 1) return 1;
22+
return n * factorials(n - 1);
23+
}
24+
25+
console.log(factorials(5));
26+
console.log(factorials(10));
27+
console.log(factorials(0));
28+
console.log(factorials(1));
29+
console.log(factorials(3));
30+
console.log(factorials(4));
31+
32+
// using while looop
33+
34+
function factorialWhile(n) {
35+
let res = 1;
36+
37+
while (n > 1) {
38+
res *= n;
39+
n--;
40+
}
41+
return res;
42+
}
43+
44+
console.log(factorialWhile(1));
45+
console.log(factorialWhile(2));
46+
console.log(factorialWhile(3));
47+
console.log(factorialWhile(105));
48+
49+
// using memoization
50+
51+
function factorialUsingMemo(n) {
52+
const cache = {};
53+
if (n === 0 || n === 1) {
54+
return 1;
55+
}
56+
if (cache[n]) {
57+
console.log("value from caeche");
58+
return cache[n];
59+
}
60+
cache[n] = n * factorialUsingMemo(n - 1);
61+
return cache[n];
62+
}
63+
console.log(factorialUsingMemo(105));

0 commit comments

Comments
 (0)