Recently i started to learn recursion in JavaScript.
i never called defined function in its own function.
what is this called?
i'm unable to understand how this recur(n - 1) working.
i tried to check how it working in chrome debugger, but there is no output too.
How here recur(n - 1) working?
function recur(n) {
if(n === 1) return 1
return n * recur(n - 1);
// How here recur(n - 1) working?
// 5 * 5 - 1 = 24
// 4 * 4 - 1 = 15
}
recur(5);
So when you do return n * recur(n - 1), the first thing that is calculated is recur(n - 1).
What happens is the following
recur(5) = 5 * recur(5 - 1)
recur(4) = 4 * recur(4 - 1)
recur(3) = 3 * recur(3 - 1)
recur(2) = 2 * recur(2 - 1)
recur(1) = 1 => the bottom of the recursion. Now it starts to go back:
recur(2) = 2 * recur(1) = 2
recur(3) = 3 * recur(2) = 3 * 2 = 6
recur(4) = 4 * recur(3) = 4 * 6 = 24
recur(5) = 5 * recur(4) = 5 * 24 = 120
Basically, until a function of recur(n - 1) returns something concrete, like the bottom of the recursion in your case 1, the method calls recur once again, and again and so on. After you go to the bottom, then the functions start to resolve in the reverse order.
The recursive function is calculating the factorial of n.
The function will call itself until it reaches a base case.
You have one base case: when n is 1 then return 1.
If you call it with say 5 then it works as follows:
recur(5) =>
5 * recur(4) =>
5 * 4 * recur(3) =>
5 * 4 * 3 * recur(2) =>
5 * 4 * 3 * 2 * recur(1) =>
5 * 4 * 3 * 2 * 1 =>
120
So the result will be 120 for n=5.
Related
please someone explain this to me
function func(x, n) {
if (n == 1) {
return x;
} else {
return x * func(x, n - 1);
}
}
console.log(func(2, 4)); // 16
how do answer is 16
I could not understand more than this
when if is false it going to else
in the return section function call itself
at the first input is the same value as x, ie 2
at the second input is n - 1
when function run again the value of x remains the same as 2 and the value of n becomes 3
that's mean 3 times if is false
in the 4 times if if true and the execution loop ends and show answer in alert
i can not figure out what number is multiplied by x per run or the answer should be the same as 2
because every time the function is executed, shouldn't the value of x be equal to 2?
If you are asking about how recursion works, then I will explain you with this basic flowchart diagram.
I also edited your JS Code so it will provide you with clarification.
function func(x, n) {
if (n == 1) {
return x;
} else {
let function_returned = func(x, n - 1);
console.log(x, "*", function_returned, "=", x*function_returned)
return x * function_returned
}
}
console.log(func(2, 4));
The function performs exponentiation. So func(x, n) is calculating xn.
It uses recursion, based on the following principle:
When n is 1, then xn = x1 = x
When n > 1, then xn = x.xn-1
For the second statement we can use the function with arguments x and n-1.
For the concrete example, func(2, 4), this is what happens:
x=2, n=4, so we get in the else block and evaluate:
2 * func(2, 3)
For this nested call of func we have x=2, n=3, and again we get in the else block for that:
2 * func(2, 2)
And again we have a nested call, which evaluates to:
2 * func(2, 1)
...and this final nested call gets into the if block and evaluates to:
2
Now we need to backtrack as each nested function call returns the result to its caller:
2 is returned for func(2, 1) which turns 2 * func(2, 1) to 4
That 4 is returned for func(2, 2) which turns 2 * func(2, 2) to 8
That 8 is returned for func(2, 3) which turns 2 * func(2, 4) to 16
And that 16 is what you get in the output
It's a recursive power function. What it does is the following:
2^4 = ?
2 * 2^3 = ?
2 * 2 * 2^2 = ?
2 * 2 * 2 * (2^1) = ? // at this point we get to n == 1 and this is where result is just x which is 2 in your example. From this point we can start moving "back"
2 * 2 * (2 * 2) = ?
2 * (2 * 4) = ?
(2 * 8) = ?
16 = ? // 16 is just 16, we're done.
Your can read a bit about recursion to get a better idea on what is going on.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to JS and I am completely stuck with this simple thing and I would really like to understand this and continue further with learning.
I have this chunk of code:
var power = function(base, exponent) {
var result = 1;
for (var count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
console.log(power(2, 10));
// Result is: 1024
A result in the console will be 1024
If I change values into:
console.log(power(1, 10));
// Result is: 1
But if I change into:
console.log(power(3, 10));
// Result is: 59049
I will get a result of 59049.
So, how I got this result of 59049? How I got a result of 1024? How I got a result of 1? How does all this thing work?
I would really appreciate if someone can explain it to me on as simplest and dummies way as possible :)
Thanks!
That's because
2 to the power of 10 (or 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) equals 1024
and
1 to the power of 10 (or 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1) equals 1
and
3 to the power of 10 (or 1 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3) equals 59049
If you supply your function with a base and an exponent, the function will do the following:
power(2, 0) yields 1 because exponent is 0 and the function immidiately returns result (which is 1) without entering the loop.
power(2, 1) yields 2 because result (which is 1) is multiplied once with base (which is 2) in your loop thus resulting in 1 * 2 = 2
power(2, 2) yields 4 because result (which is 1) is multiplied twice with base (which is 2) in your loop thus resulting in 1 * 2 * 2 = 4
power(2, 3) yields 8 because result (which is 1) is multiplied three times with base (which is 2) in your loop thus resulting in 1 * 2 * 2 * 2 = 8
This javaScript code block is making me crazy,that how it is doing the computation behind. I try to manually do it with calculator but the results start to be different at 4. Please explain if you know how
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
if i run console.log(fac(1));
// > 1
if i run console.log(fac(2));
// > 2
if i run console.log(fac(3));
// > 6
i was thinking this is what was happening behind
(2-1) * 2 = 2,
(3-1) * 3 = 6,
until i put
(4-1) * 4 = 12.
if i run console.log(fac(4)); the output is 24 not 12
// > 24 how and why?
cheers
It is performing recursive function call to the same function.
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
fac(4);
Value of n is 4. So it should returnfac(4 - 1) * 4). Now fac(4 -1) is calculated before returning the value.
Value of n is 3. Now it will return fac(3 - 1) * 3), which replaces fac(4 - 1) in previous statement. So, it will become fac(3 - 1) * 3 * 4.
Value of n is 2. Now it will return fac(2 - 1) * 2), which replaces fac(3 - 1) in previous statement. So, it will become fac(2 - 1) * 2 * 3 * 4.
Value of n is 1. Now it will return fac(1 - 1) * 1), which replaces fac(2 - 1) in previous statement. So, it will become fac(1 - 1) * 1 * 2 * 3 * 4.
Value of n is 0. Now it will return 1, which replaces fac(1 - 1) in previous statement. So, it will become 1 * 1 * 2 * 3 * 4.
As you can see, you can avoid multiplying by 1 twice by changing your code to
function fac(n) {
if (n == 1)
return 1;
else
return fac(n - 1) * n;
}
In short,
function fac(n) {
return (n == 1) ? 1 : (fac(n - 1) * n);
}
That's a factorial. It's calculates all permutation a set with n elements has. Or simpler:
[factorial] is the product of all positive integers less than or equal to n.
Wikipedia:Factorial
It's noted as n!. For example:
1! = 1
2! = 1 * 2 = 2
3! = 1 * 2 * 3 = 6
4! = 1 * 2 * 3 * 4 = 24
What the function is doing is recursively calling itself. When you execute the function fac(4) the following happens:
At fac(4), since 4 != 0 the value returned is fac(4 -1) * 4. However, since the return function contains a reference to a function, we wait for it to return a value.
At fac(3) (i.e. fac(4-1)), since 3 != 0 the value returned is fac(3-1) * 3. However same thing happens and we wait for result of fac(3-1)/fac(2).
At fac(2) (i.e. fac(3-1)) since 2 != 0 the value returned is fac(2-1) * 2. Again, since we are calling a function we wait for its return until we proceed will calculation.
At fac(1) (i.e. fac(2-1)) since 1 != 0 the value returned is fac(1-1)* 1 and we defer for fac(1-1) to return result.
At fac(0) (i.e. fac(1-1)) since 0==0 we return value one which is neutral for multiplication.
In fac(1), fac(1-1) becomes one, so fac(1) value becomes 1*1 or 1.
In fac(2), fac(2-1) is replaced with 1 so fac(2) becomes 1*2 or 2.
In fac(3), fac(3-1) is replaced with 2, and fac(3) becomes 2*3 or 6.
In fac(4), fac(4-1) is repalced with 6 and fac(4) becomes 6*4 or 24.
This question already has answers here:
Recursive power function: Why does this work if there's no initial return value?
(6 answers)
Closed 8 years ago.
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
If I change it to return 2, it doubles the answer, 3 triples etc.
I understand what it's doing, but I haven't learned how it knows to produce a multiple of the return from the 'else' part. Please explain.
EDIT: While I'm here, how is the else working? I would assume base is being multiplied by base, and then the exponent is subtracting from itself, but when I do something like: base * (2, 5-1) it multiplies base by 4... I must be missing something simple.
If you return 1, then calling power(7, 3) will result in:
7 * 7 * 7 * 1
If you return 2, then it will result in:
7 * 7 * 7 * 2
where the last number is the number that you are returning.
Do you now see why changing the return value doubles the result?
To answer your second question, this due to the behavior of the comma operator, which evaluates to the value of the expression after the last comma so:
base * (2, 5 - 1)
base * (5 - 1)
base * (4)
This is completely unrelated to calling a function with the parameters 2 and 5 - 1.
It doesn’t have to "know" anything. It keeps recurring until the exponent is zero.
how is the else working?
If exponent != 0 it runs, its the opposite of the if.
This is a recursive function that calls itself over and over until it finds the correct answer. Tracing the way the function works should help you understand it.
Take power(2, 5) for example.
power(2, 5) = 2 * power(2, 4)
= 2 * 2 * power(2, 3)
= 2 * 2 * 2 * power(2, 2)
= 2 * 2 * 2 * 2 * power(2, 1)
= 2 * 2 * 2 * 2 * 2 * power(2, 0)
= 2 * 2 * 2 * 2 * 2 * 1
All together, you end up with 2 * 2 * 2 * 2 * 2 * 1 which is 25, as expected. The else in your function gets triggered when the exponent parameter (the 5 in the example) is greater than zero. Since 5 is greater than 0, the else part is triggered and the function is called again with 4 as the exponent. Since 4 is greater than 0, the else part is triggered and the function is called again with 3 as the exponent. The same thing happens with 2, then 1, then 0. When power(2, 0) is finally called, the function just returns 1.
I have the following example of a recursive function, and what I don't understand is the order in which things are happening:
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
When does the function return the values, at the end of all the process or each time?
A simple way to visualize what happens in recursion in general is this:
a stack of calls to the function is created: this process needs a proper termination condition to end (otherwise you'll have infinite recursion, which is evil)
the single results are popped out of the stack: each result is used to calculate the next step, until the stack is empty
I.e. if base=5 and exponent=3, the call stack is (last element on top):
5*(5*(5*1))
5*(5*(5*power(5, 0)))
5*(5*power(5, 1))
5*power(5, 2)
power(5, 3)
then every called function has real parameters and is ready to return a value (first element on top):
5*(5*(5*1))
5*(5*5)
5*25
125
Note that here the functions are calulated in inverse order: first power(5, 0), then power(5, 1), and so on.. After each calulation an element of the stack is released (i.e. memory is freed).
Hope it helps :)
It is generally helpful in understanding recursive functions such as this to work things out like you would in an algebra class. Consider:
power(3, 4)
= 3 * power(3, 3)
= 3 * (3 * power(3, 2))
= 3 * (3 * (3 * power(3, 1)))
= 3 * (3 * (3 * (3 * power(3, 0))))
= 3 * (3 * (3 * (3 * 1)))
= 3 * (3 * (3 * 3))
...
= 81
The key here is that power is calling itself exactly in the way it could call any other function. So when it does that, it waits for the function to return and uses its return value.
So if you do
var x = power(10, 2);
Your call to power will get to this line:
return base * power(base, exponent - 1)
...and call power(10, 1), waiting for that to return.
The call to power(10, 1) will, of course, get to the line:
return base * power(base, exponent - 1)
...and call power(10, 0), waiting for that to return.
The call to power(10, 0) will return 1, which is then used by the call in #2 above to complete its work and return 10 * 1 = 10, which will then let your original call in #1 above return the value 10 * 10 = 100.
When seeking to understand things like this, there's nothing quite like walking through the code with a debugger. In this modern world, you have plenty to choose from, many of which may already be on your computer.
For better visualization, just substitute the function call with the function body (may be pseudo code for instance).
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
power(5, 3) expands to this
function power(5, 3) {
// exponent 3 is not 0
// return 5 * power(5, 3-1)
return 5 * function power(5, 2) {
// exponent 2 is not 0
// return 5 * power(5, 2-1)
return 5 * function power(5, 1) {
//exponent 1 is not 0
// return 5 * power(5, 1-1)
return 5 * function power(5, 0){
//exponent 0 is 0
return 1;
}
}
}
}
Now the picture is clear. It all becomes like below..
// 1
function power(5, 3){
return 5 * function power(5, 2){
return 5 * function power(5, 1){
return 5 * ( function power(5, 0){
return 1;
} )
}
}
}
// 2
function power(5, 3){
return 5 * function power(5, 2){
return 5 * ( function power(5, 1){
return 5 * 1;
} )
}
}
// 3
function power(5, 3){
return 5 * ( function power(5, 2){
return 5 * 5 * 1;
} )
}
// 4
function power(5, 3){
return ( 5 * 5 * 5 * 1 );
}
// 5
5 * 5 * 5 * 1;
As with any recursive function, the return from a particular "instance" happens when the return value has been calculated. This means that the recursed versions will then have been calculated.
So if you pass in an exponent of 4, there will be at some point 4 copies of the function being executed at one time.
This line and its resolution really trips me up:
return base * power(base, exponent - 1)
I get that the exponent is decremented until it meets the base case, but when you mulitply
the base times the recursive function call, I keep thinking "how does the function mulitply the base by itself(the base arguement)?", where is it doing that exactly, because calling base * power(base, exponent - 1) doesn't look like the standard loop contruction. How can it be calling a function with two arguements, how does it know to skip the exponent arguement and multiply the base by the base?
From a mathematical perspective:
let x = base,
let n = exponent
x*x^(n-1) = x^n
because
x^1*x^n-1=x^n (exponents of like term adds together)
It is the same as:
base * base*exponent-1.