Multiplication in for loop [closed] - javascript

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

Related

unable to understand recursive pattern and its function call

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.

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.

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 :)

Return 1 in javascript [duplicate]

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.

Javascript - Do counting variables never hit 0?

In the code below, how does the code know to do something like this, if n = 8:
8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
instead of doing * 0 at the end? Does the counting variable (n, or any counting variable ever) never hit 0 when using n--?
var n = document.getElementById("selNumber").value;
var result = 1;
while(n) {
result *= n;
n--;
}
Because when n = 0, the 0 is interpreted as false and the loop is never entered.

Categories