.Js
Function that calculates the factorial of a given number:
You can create a function to calculate the factorial of a given number using recursion or iteration. Here's how you can implement it using recursion:
function factorial(n) {
// Base case: factorial of 0 is 1
if (n === 0) {
return 1;
}
// Recursive case: n * factorial(n-1)
return n * factorial(n - 1);
}
// Example usage:
console.log(factorial(5));
// Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)
And here's how you can implement it using iteration:
function factorial(n) {
let result = 1;
// Multiply result by each integer from 1 to n
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Example usage:
console.log(factorial(5));
// Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)
120
Explanation:
Both implementations achieve the same result. The recursive implementation calls itself with a smaller value until it reaches the base case (factorial of 0), while the iterative implementation uses a loop to multiply each integer from 1 to n to calculate the factorial. Choose the one that suits your preference or requirements.
• Learn in-depth concepts of factorial number from the algorithm page.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.