Skip to content

Commit 5b79e2c

Browse files
author
Sruthi U
committed
Added factorial function
1 parent 5c39e87 commit 5b79e2c

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

‎factorial.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
2+
// Function to calculate factorial
3+
4+
function factorial(n) {
5+
if (!Number.isInteger(n) || n < 0) {
6+
throw new Error("Enter a non-negative integer");
7+
}
8+
9+
if (n === 0 || n === 1) {
10+
return 1;
11+
}
12+
13+
return n * factorial(n - 1);
14+
}
15+
16+
// Example usage
17+
console.log(factorial(5)); // Output: 120

0 commit comments

Comments
 (0)