Return 1 in javascript [duplicate] - javascript

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.

Related

javascript explain this code function call it self

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.

Multiplication in for loop [closed]

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

Confusion in eloquent javascript power recursion sample

this recursion code is from the book of eloquent javascript
function power(base, exponent) {
if (exponent == 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
}
console.log(power(2, 3));
obviously the exponent is decreased until it reached 0, if it is not zero, it adds power call on the stack, if it is zero, I start to see the return value of 1 then 2 then 4 then 8. But how did base got multiplied by exponent, how did base see the exponent value? it's on else and on power call?
But how did base got multiplied by exponent
It doesn't multiply by the exponent.
The exponent is being used as a counter to end the recursive cycle once it's been reduced to 0. The base is instead being multiplied by itself an exponent number of times.
This is supported by each call to power() returning either 1 or the value of base. In the latter case, power() is called again to get 1 or another copy of base to multiply by. And, this repeats until it does finally return 1 as the final multiplier.
power(2, 3) ==
2 * power(2, 2) == // base * ...
2 * 2 * power(2, 1) == // base * (base * ...)
2 * 2 * 2 * power(2, 0) == // base * (base * (base * ...))
2 * 2 * 2 * 1 // base * (base * (base * (1)))
The same steps could also be defined with a loop, though using 1 as the initial value rather then at the end:
function power(base, exponent) {
var result = 1;
while (exponent) {
result *= base;
exponent--;
}
return result;
}
console.log(power(2, 3)); // 1 * base * base * base == 1 * 2 * 2 * 2 == 8
I find it easy to understand recursive procedures by looking at their base case first, then building up from there – here's the function we're studying...
function power(base, exponent) {
if (exponent == 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
}
So here, the base case is exponent == 0. We'll keep 2 as the input for base:
power(2, 0) => 1
Well that was really easy! All we had to do was evaluate an if statement and we arrived at our answer. Looking ahead, we see that power arrives at its base case by subtracting 1 from the exponent (exponent - 1), we'll reverse this to get our next input – so instead of power(2, 0) we will do power(2, 1)
power(2, 1) => 2 * power(2, 0)
=> but wait! don't re-evaluate power(2,0)! we already know that answer from above
=> 2 * 1
=> 2
Ok, we'll keep doing the same thing by incrementing exponent by 1 each time. But be careful not to do unnecessary work – if we've already evaluated one of the expressions earlier, just replace that expression with it's evaluated value
power(2,2) => 2 * power(2, 1)
=> we already know power(2,1) == 2 ...
=> 2 * 2
=> 4
power(2,3) => 2 * power(2,2)
=> we already know power(2,2) == 4, etc
=> 2 * 4
=> 8
power(2,4) => 2 * power(2,3)
=> 2 * 8
=> 16
power(2,5) => 2 * power(2,4)
=> 2 * 16
=> 32
Now we can easily see a pattern and how the recursive procedure works in general
What you have to notice is that the power function
returns 1 when exponent is 0 and
return base * power() on another case.
Pay attention to power function
In the following code
power(base, exponent - 1);
you have to appreciate some things
1) If exponent is 1 the function power returns 1 so in here
return base * power(base, exponent - 1);
Whether base is 2
return 2 * 1
The function power is returning 2, so in the next step
return base * power(base, exponent - 1);
means
return 2 * 2;
which is 4, that means that function power is returning 4
I think you can catch up from here.
Let me know if you understood :)

Eloquent JavaScript: Can't understand recursion example [duplicate]

This question already has answers here:
How does Eloquent JavaScript recursion example terminate as return 1 but still output exponential value
(2 answers)
Closed 7 years ago.
From page 50 of Haverbeke's second edition. I added a couple of console.log to try to better track the progress.
function power(base, exponent) {
if (exponent == 0) {
console.log("line 5 " + base + " " + exponent);
return 1;
}
else
console.log("line 10 " + base + " " + exponent);
return base * power(base, exponent -1);
}
console.log(power(2,3));
// Output
line 10 2 3
line 10 2 2
line 10 2 1
line 5 2 0
8
//
I expect the final output to be 1 since when the if (exponent == 0) is true, the next statement is return 1;, but it appears to enter the else one more time to return 8. But shouldn't the return kick us out of the function.
Obviously a newbie or wouldn't be stuck on page 50 of a supposedly beginner book.
Thanks for any help.
Whenever the function enters the "else" branch, a new stack frame is created, waiting for the result of the recursive call. You can imagine the evaluation step by step:
power(2, 3) enters the else branch, and it returns base * power(base, exponent - 1).
2 * power (2, 2) enters the else branch, and it returns base * power(base, exponent - 1).
2 * (2 * power (2, 1)) enters the else branch, and it returns base * power(base, exponent - 1).
2 * (2 * (2 * power (2, 0))) enters the if branch, and it returns 1.
You can finally evaluate the result: 2 * (2 * (2 * 1)), which is 8.
The end result of the function call power(2,3) is not the last return, but the combination of returned values, by the subsequent internal function calls. Let's deconstruct the recursive function:
power(2,3) returns 2 * power(2,2)
power(2,2) returns 2 * power(2,1)
power(2,1) returns 2 * power(2,0)
power(2,0) returns 1
So in total, power(2,3) returns 2 * 2 * 2 * 1 which is equal to 8.
The return statement exits from one invocation of the function. In order to get to the return 1; line, the function will have been called several times (based on the original value of the exponent).
The first invocation is
console.log(power(2,3));
Inside the function, subsequent invocations take place here:
return base * power(base, exponent -1);
Each one will correspond with a return.
Oh, and as #TJCrowder notes in a comment, that code is not correct: the else part should be wrapped in { }:
if (exponent == 0) {
console.log("line 5 " + base + " " + exponent);
return 1;
}
else {
console.log("line 10 " + base + " " + exponent);
return base * power(base, exponent -1);
}
I'm assuming that the missing { } wrapper was a transcription error.

How exactly does this recursive function work in JavaScript?

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.

Categories