🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The factorial of a number is the product of all positive integers less than or equal to that number. In JavaScript, you can compute the factorial using various methods such as recursion, iteration, and higher-order functions. This guide will walk you through different ways to compute the factorial in JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a positive integer.
- Calculates and returns the factorial of that number using different methods.
Example:
Input:
5Output:
120Input:
3Output:
6
Solution Steps
- Read the Input Number: Accept or define the number directly in the program.
- Handle Base Case: Return
1if the input number is0or1. - Calculate Factorial: Implement different methods (recursion, iteration, functional programming).
- Display the Result: Output the calculated factorial for each method.
Method 1: Recursive Approach
// JavaScript Program to Find the Factorial of a Number Using Recursion
// Author: https://www.javaguides.net/
function factorialRecursive(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
let number = 5;
let result = factorialRecursive(number);
console.log(`The factorial of ${number} using recursion is: ${result}`);
Output:
The factorial of 5 using recursion is: 120
Explanation:
- This function uses recursion to calculate the factorial. The base case returns
1for0!and1!. For other numbers, it recursively multiplies the number byfactorial(n-1).
Method 2: Iterative Approach
// JavaScript Program to Find the Factorial of a Number Using Iteration
// Author: https://www.javaguides.net/
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
result = factorialIterative(number);
console.log(`The factorial of ${number} using iteration is: ${result}`);
Output:
The factorial of 5 using iteration is: 120
Explanation:
- The iterative approach uses a
forloop to calculate the factorial. It starts from1and multiplies by each subsequent number until it reachesn.
Method 3: Using Higher-Order Functions (Array reduce)
// JavaScript Program to Find the Factorial of a Number Using Array reduce
// Author: https://www.javaguides.net/
function factorialUsingReduce(n) {
if (n === 0 || n === 1) {
return 1;
}
return [...Array(n).keys()].map(i => i + 1).reduce((acc, val) => acc * val, 1);
}
result = factorialUsingReduce(number);
console.log(`The factorial of ${number} using reduce is: ${result}`);
Output:
The factorial of 5 using reduce is: 120
Explanation:
- This method leverages JavaScript’s
Array.reduce()to calculate the factorial. An array from1tonis created and then reduced by multiplying each element.
Conclusion
This JavaScript program demonstrates three methods to calculate the factorial of a number:
- Recursion is elegant but can be less efficient for large numbers due to stack overflow risks.
- Iteration is straightforward and memory efficient.
- Array reduce provides a functional programming approach, making the code concise and leveraging JavaScript’s higher-order functions.
Each method has its own advantages depending on the scenario and size of the input number.
Comments
Post a Comment
Leave Comment