Day 5 – Factorial of a Number in JavaScript: Recursion vs Loop
๐ฅ JavaScript DSA Interview Series – Day 5
๐ง Problem: Find the factorial of a number using both loop and recursion
---
✅ What is Factorial?
The factorial of a number n is the product of all positive integers less than or equal to n.
๐ n! = n × (n−1) × (n−2) × ... × 1
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
---
๐ Iterative (Loop) Approach:
function factorialLoop(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
---
๐ Recursive Approach:
function factorialRecursive(n) {
if (n === 0 || n === 1) return 1;
return n * factorialRecursive(n - 1);
}
---
⚠️ Edge Case:
0! is 1
Negative numbers are not valid for factorial
---
๐ก Tips to Remember:
Use recursion only for small inputs (can cause stack overflow)
Loop is efficient and safe for interviews
Recursive solution shows understanding of function calls and base conditions
http://youtube.com/post/Ugkx1JuFK5mB2cSUAX8Yu0N6eFe8RuioUQ3Z?si=vN94FOnh01Dqq6A-
Comments
Post a Comment