Write a recursive JS program to calculate the factorial of a number.
For example. 5! = 5 * 4 * 3 * 2 * 1 = 120
One easy way to set this up is to create a base case that returns 1, once the decremented number reaches 1. By decremented number, I mean the recursive call the number being fed is decremented each time until 1 is reached. Then all the numbers come back and multiply themselves together.
Since this first one is easy, I'm going to walk through it, incase you're unfamiliar with recursion :
var factorial = function(num){
if(num === 1){
return 1;
}
return num * factorial(num -1);
}
var maple = factorial(9);
maple will equal 362880
First, the factorial function takes 9 as an argument, checks to see if it is equal to 1, it's not, it returns the value of 9 multiplied by the value received from calling the function factorial on 8. This function is just calling itself rather than another function. That value is then calculated by feeding 8 to another instance of factorial, it checks to see if 8 is equal to 1, it's not, so it returns the value of 8 multiplied by the value of calling factorial and feeding it 7.
This goes on and on until 1 is reached. At this point the function returns 1 as the value. That means that the function that had multiplied 2 by the value of factorial being fed 1, now has received the value from factorial being fed 1, that value is 1. So 2 will be multiplied by 1, and that equals 2, and that will be returned to the function before it, that had called factorial and fed it a 3 and had returned the value 3 multiplied by the value of factorial fed 2. Well, that factorial fed 2 now has a value, and that value is 2. So, 3 times 2 is six, and this value gets returned to the function that is waiting for that value, and so on, and so on, until we reach the very first function that started all this.
It may take a while to wrap one's head around.
No comments:
Post a Comment