Recursion Simple Problems - rohit120582sharma/Documentation GitHub Wiki
Without tail call
function pow(base, power){
// Base condition
if(power <= 0){
return 1;
}
// Change input and recursion
return base * pow(base, power-1); //tail call === false
}
With tail call
function pow(base, power){
if(power <= 0){
return 1;
}
// Call helper function
return helper(base, power, base); //tail call === true
}
function helper(base, power, num){
// Base condition
if(power === 1){
return num;
}
// Change input and recursion
return helper(base, power - 1, base * num);
}
Write a function factorial which accepts a number and returns the factorial of that number. A factorial is the product of an integer and all the integers below it; e.g., factorial four (4!) is equal to 24, because 4 * 3 * 2 * 1 equals 24. factorial zero (0!) is always 1.
function factorial(num){
// Base Case
if(num <= 1){
return 1;
}
// Change input and recursion
return num * factorial(num-1);
}
Write a recursive function called fib which accepts a number and returns the nth number in the Fibonacci sequence. Recall that the Fibonacci sequence is the sequence of whole numbers 1, 1, 2, 3, 5, 8, ... which starts with 1 and 1, and where every number thereafter is equal to the sum of the previous two numbers.
function fib(n){
// Base Case
if(n <= 2){
return 1;
}
// Change input and recusrion
return fib(n-1) + fib(n-2);
}