FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Add JavaScript factorial examples · commitRahul/basic-programs@a45c82b · GitHub

Commit a45c82b

Browse files
committed
Add JavaScript factorial examples
1 parent e1a138f commit a45c82b

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function factorial(n) {
2+
if (n < 0 ) throw new Error('Argument must be a positive integer.');
3+
4+
let result = 1;
5+
6+
for (let i = 2; i <= n; i++) {
7+
result = result * i;
8+
}
9+
10+
return result;
11+
}
12+
13+
const inputs = [4, 6, 8, 2, -1];
14+
15+
inputs.forEach(n => {
16+
console.log(`Factorial of ${n}: ${factorial(n)}`);
17+
});
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function factorial(n) {
2+
if (n < 0 ) throw new Error('Argument must be a positive integer.');
3+
4+
if (n === 0 || n === 1) return 1;
5+
6+
return n * factorial(n - 1);
7+
}
8+
9+
const inputs = [4, 6, 8, 2, -1];
10+
11+
inputs.forEach(n => {
12+
console.log(`Factorial of ${n}: ${factorial(n)}`);
13+
});

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL