Published on January 26, 2024By DeveloperBreeze
// Recursive function to calculate factorial
function calculateFactorialRecursive(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * calculateFactorialRecursive(n - 1);
}
}
// Iterative function to calculate factorial
function calculateFactorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Example usage
const numberToFactorialize = 5;
const recursiveResult = calculateFactorialRecursive(numberToFactorialize);
const iterativeResult = calculateFactorialIterative(numberToFactorialize);
console.log(`Factorial of ${numberToFactorialize} (Recursive):`, recursiveResult);
console.log(`Factorial of ${numberToFactorialize} (Iterative):`, iterativeResult);
Comments
Please log in to leave a comment.