Skip to content

Commit a907a95

Browse files
Update Factorial of a Number.js
1 parent 442c2fc commit a907a95

1 file changed

Lines changed: 25 additions & 15 deletions

File tree

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,28 @@
11

2-
// ****************************************************************************** Factorial *******************************************************************************
2+
// *************************************************************** Generate Factorial of a Number in Different Ways **********************************************************
33

4-
// 1. Find Factorial of a Number:
5-
// Find factorial using loop:
6-
function factorial(n) {
4+
// 1. Generate Factorial of a Number:
5+
6+
// factorial using for loop:
7+
function factorial(n)
8+
{
79
let fact = 1;
8-
for (let i = 1; i <= n; i++) {
10+
for (let i = 1; i <= n; i++)
11+
{
912
fact *= i; // fact = fact * i;
1013
}
1114
return fact;
1215
}
1316
console.log("Factorial using For Loop:", factorial(5));
1417
// Output:
15-
// Factorial (using For Loop): 120
18+
// Factorial using For Loop: 120
1619

17-
// 2. Find factorial Using Recursion:
18-
function factorial(n) {
19-
if (n <= 1) return 1;
20+
// 2. factorial Using Recursion:
21+
function factorial(n)
22+
{
23+
if (n <= 1){
24+
return 1;
25+
}
2026
return n * factorial(n - 1);
2127
}
2228
console.log("Factorial using Recursion:", factorial(5));
@@ -25,16 +31,20 @@ console.log("Factorial using Recursion:", factorial(5));
2531

2632
// OR
2733

28-
// Find factorial Using Recursion:
29-
function factorial(n) {
30-
if (n === 0 || n === 1) {
34+
// factorial Using Recursion (with If-Else):
35+
function factorial(n)
36+
{
37+
if (n === 0 || n === 1)
38+
{
3139
return 1;
32-
} else {
40+
}
41+
else
42+
{
3343
return n * factorial(n - 1);
3444
}
3545
}
3646
const number = 5;
3747
const result = factorial(number);
38-
console.log("Factorial of", number, "is", result);
48+
console.log("Factorial of", number, "is:", result);
3949
// Output:
40-
// Factorial using Recursion: 120
50+
// Factorial of 5 is: 120

0 commit comments

Comments
 (0)