Iteration vs Recursion
· 3 min read
Staying out of the loop with recursion.
Iteration
- Imperative looping stateful.
- Using loops to do Iteration.
Example
function sum(numbers) {
let total = 0;
for (i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
sum([0, 1, 2, 3, 4]); // 10
Problem: Find the factorial of number using Iteration
Example 5! = 5 x 4 x 3 x 2 x 1
Factorial(1) = 1; // base condition
Factorial(2) = 2 * 1 = 2 * Factorial(1);
Factorial(3) = 3 * 2 * 1 = 3 * Factorial(2);
Factorial(4) = 4 * 3 * 2 * 1 = 4 * Factorial(3);
Factorial(5) = 5 * 4 * 3 * 2 * 1 = 5 * Factorial(4);
Factorial(n) = n * Factorial(n-1) // recursive condition
function factorial(n) {
let fact = 1;
for (let i = 5; i > 0; i--) {
fact *= i;
}
return fact;
}
console.log(factorial(5)); // return 120
Fanocci Number find usign Iterative
function iterativeFabnocci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let previous = 0;
let current = 1;
for (let i = n; i > 1; i--) {
let next = previous + current;
previous = current;
current = next;
}
return current;
}
console.log(iterativeFabnocci(6));
Recursion
- functional self-referential stateless.
- When a function is recursive, it continues to call itself until a non-recursive base case is reached.
Example
A recursive function has two parts:
- Base Case : stop the execution by calling it self if the length is 1. if we not added it, it goes to infit loop.
- It is condition(s) under which the function returns an output without making a recursive call.
- Base condition is the one which doesn’t require fo call the same function again and it helps in stopping the recursion.
- Recursive Case: calling itself function until the last element.It is condition(s) under which the function calls itself to return the output.
function sum(numbers) {
if (numbers.length === 1) {
// base case
return numbers[0];
} else {
// recursive case
return numbers[0] + sum(numbers.slice(1));
}
}
sum([0, 1, 2, 3, 4]); // 10
Problem: Find the factorial of number using recursive
function factorial(n) {
if (n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5)); // return 120
Fabnocci Number using Recursive Func
function recursiveFabnocci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return recursiveFabnocci(n - 1) + recursiveFabnocci(n - 2);
}
console.log(recursiveFabnocci(6));
Are recursive functions more expensive than iterative functions?
Exercise
Comparing performance
- Recursive has less performance then iterative the reason is that Recursive call again and again itself.
- Another reason is that call stack, it call too much recursion.
- Recursion throw error "Internal Error: too much recursion" in Firefox if we adding the 10,000. to solve this error using Trail call Optimization.
- Using memorization(cache) in the recursion the result that can help to re-again calculate the computation in the recursion.