Javascript Function that validates exponent equations - javascript

This is a hw assignment. The answer/output I want is correct. I just don't understand why. I want the output to be true if the power function matches the number I am checking against. I do get the answer true for these examples, but I don't understand how this recursive function is working.
In the else of this function, I am saying base * the function itself. what does that even represent? How can base * power(base, exponent - 1); even compute? Shouldn't it just run in a circle and then finally end?
console.log(power(2,4) === 16);
console.log(power(2,3) === 8);
console.log(power(2,2) === 4);
var power = function(base, exponent) {
if(exponent === 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
};

The function power returns an integer, so when the function returns base * <some_integer> is a perfectly valid expression. The best way to trace these things is with a pen and paper:
call stack of power(2,4):
power(2, 4) = 2 * power(2, 3)
power(2, 3) = 2 * power(2, 2)
power(2, 2) = 2 * power(2, 1)
power(2, 1) = 2 * power(2, 0)
power(2, 0) = 1 <--base case
now all you have to do is substitute the values up the call stack
power(2, 4) = 2 * 8 = 16
power(2, 3) = 2 * 4 = 8
power(2, 2) = 2 * 2 = 4
power(2, 1) = 2 * 1 = 2

It might help to write the function using Javascript's syntactic sugar declaration style:
console.log(power(2,4) === 16);
console.log(power(2,3) === 8);
console.log(power(2,2) === 4);
function power(base, exponent) {
if(exponent === 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
};
If you want, you can also add the line
console.log("power("+base+", "+exponent+")");
at the head of the function, to watch the recursive call sequence.

The exponent is being reduced with each recursive call until it is equal to 0 where it will return a constant 1, and the function stops being recursive.
jsFiddle.
Also, if this wasn't homework, there is Math.pow() :)

For the example of power(2,4), we have
4 != 0 so else executes and it performs 2*power(2,3).
3 != 0 so else executes and it performs 2*power(2,2).
2 != 0 so else executes and it performs 2*power(2,1).
1 != 0 so else executes and it performs 2*power(2,0).
Finally 0 == 0 so it returns 1 and it doesnt perform another recursive call.
So it goes back through the calls and comes to 2*power(2,0) which we know power(2,0) == 1. That returns as 2.
Then it goes back to 2*power(2,1) and we know power(2,1) == 2 since [2*power(2,0)]. This returns as 4.
See the pattern? And so on until we get back to 2*power(2,3) ==16 since we have power(2,3) == 8 since [power(2,2) * power(2,1) * power(2,0) * 1]. Hope this helped!

Related

How does a recursive function work in javascript [duplicate]

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.

Confusion about the behavior between arithmetic operators and functions?

function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(2, 3) ); // 8
source = https://javascript.info/recursion
Hello all! I'm confused about the second return statement of this function:
return x * pow(x, n - 1);
I'm just looking for either some clarification or a reference to that behavior.
From my perspective, it looks like x is multiplied only by the first parameter of the function, and the n-1 is ignored.
(How does n-1 affect the result <- original question)
Sorry, I messed up the original question...
I want to ask how does javascript interprets that multiplication. When multiplying an integer and a function, I don't quite understand what's happening. How does javascript choose what to multiply with more than one parameter?
pow(2, 3) = 2 * pow(2, 2) = 2 * 2 * pow(2, 1) = 2 * 2 * 2
You are not actually calculating a product with n - 1, but refer to n as a counter. This is equivalent to
var result = 1;
while (n >= 0) {
result *= x;
n--;
}

JavaScript: Trying to Understand The Else Statement of a Recursion Function Calculating Exponent Value

I want to calculate exponents using recursion. I have the code below which executes successfully.
function pow(base, exponent) {
if (exponent <= 1){
return base
}
else {
return base * pow(base, exponent-1)
}
}
// console.log(pow(3, 5)); // -> answer is 243
I am trying to understand the else case here. In the else statement when the input argument for exponent is 2 or higher:
what does the pow(base, exponent-1) portion of return base * pow(base, exponent-1) return? Does it equal the base value?
So if you want to calculate `pow(2, 3) -- that is 2 raised to the 3rd power, or 8 -- this function does
(if)
since 1 <= 1 ------+
(else) |
since 2 > 1 ------+ |
| |
(else) | |
since 3 > 1 ------, | |
V V V
pow(2, 3) ---> 2 * pow(2, 2) ---> 2 * 2 * pow(2, 1) ---> 2 * 2 * 2 -> 8
This is the essence of recursion: calling a function from inside the same function (or at least somewhere in the call-stack; see mutual recursion examples), using data that is in some way simpler; so that eventually you hit a base case you can calculate without such calls.
Consider that 2 ** 3 == 2 * (2 ** 2)
and 2 ** 2 == 2 * (2 ** 1)
Substituting gives:
2 ** 3 == 2 * 2 * (2 ** 1)
This is all your recursive function is doing. When you call:
pow(2, 3)
That turns into:
base * pow(2, 2)
pow(2, 2) turns into:
base * pow(2, 1)
substitute give:
base * base * pow(2, 1)
pow(2, 1) is your base case which equals base so in the end you get
pow(2, 3) === base * base * base
One of the best tools for understanding recursion is the debugged. Just step through and see how the values are changing and what's on the stack.
It's a recursion function. Consider the recursion function F(n) in mathematic.
F(n, m) = n * F(n , m-1),
F(n, 1) = n.
So, the code just implement this function.
F(n) in the code is pow(base, exponent) which n is base and m is exponent.
On each recursion, the function is called with 1 less than the exponent initially passed.
pow(base, exponent-1)
essentially counting down from it's initial value to 1, at which point it meets the condition where it stops recursing, and only returns the base.
if (exponent <= 1){
return base
}
so if you pass pow(3, 4),
recursion 1 (pow(3,4)): 3 * // 3
recursion 2 (pow(3,3)): 3 * // 9
recursion 3 (pow(3,2)): 3 * // 27
recursion 4 (pow(3,1)): 3 = // 81

Exponent code, i don't understad code behaviour

This is the code for exponent compute:
var exponent = function(a, n){
if(n === 0) {
return 1;
}
else {
return a * exponent(a, n-1)
}
};
console.log(exponent(5,3));
I don't understand this line:
return a * exponent(a, n-1)
What does exponent(a, n-1) mean? Especially n-1?
In your example
exponent(5, 3)
On that line, it equal to
5 * exponent(5, 2) // 2 = 3 - 1
then, it equal to
5 * (5 * exponent(5, 1)) // 1 = 2 - 1
= 5 * (5 * (5 * exponent(5, 0))) // 0 = 1 - 1
= 5 * (5 * (5 * 1)) // exponent(5, 0) = 1 because n === 0
...
Your function is using recursion, and thus it is calling itself within the function.
Let your function exponent be exp for this explanation.
Let's say you want to calculate 5^3 (five to the power of three). This is the same as writing exp(5, 3):
exp(5, 3) will return 5 * exp(5, 2)
But, we don't know what exp(5, 2) is yet, so we need to work that out (by using our function again)
exp(5, 2) will return 5 * exp(5, 1)
Again, we don't know what exp(5, 1) is yet, so we also need to figure that out.
exp(5, 1) will return 5 * exp(5, 0)
Once again, we still don't know what exp(5, 0) is, so we need to let our function calculate this. However, doing this will tirgger our base case as x^0 will always give you 1. The base case is what allows the recursive calls to finish (as another call to a function isn't used). Thus:
exp(5, 0) will return 1.
Now that we know what all our functions give, we can traverse back up our functions calls:
exp(5, 1) returned 5 * exp(5, 0), which is 5 * 1 which equals 5
exp(5, 2) returned 5 * exp(5, 1), which is 5 * 5 which equals 25
exp(5, 3) returned 5 * exp(5, 2), which is 5 * 25 which equals 125
And thus, you finally get your result of:
exp(5, 3) = 125
Thus, the n-1 acts somewhat like a counter, bringing you closer and closer to your base case (ie: if(n == 0)) and managing how many times to recursively call your function.
This is a recursive function. The recursive call counts down from n to 1 by calling itself with n-1 as argument. So you get this:
exponent(5, 0) == 1
exponent(5, 1) == 5 * exponent(5, 1 - 1) == 5 * exponent(5, 0) == 5 * 1 == 5
exponent(5, 2) == 5 * exponent(5, 2 - 1) == 5 * exponent(5, 1) == 5 * 5 * exponent(5, 1 - 1) == 5 * 5 * exponent(5, 0) == 5 * 5 * 1 == 25
// ... and so on
So n - 1 is essentially a counter, counting down the number of times the function still has to repeat itself.
This is a recursive function for calculating a raised to a power n. If the exponent is 0, you're done and 1 is returned. Otherwise a times the result of a raised to the power n-1 is returned - which is recursive...
Your function is a recursive function, lets say a = 2 and n = 3,
on your first iteration, n = 3 - 1 = 2and a = 2 * 2 = 4 since n = 2 != 0, your function iterates again,
second iteration, n = 2 - 1 = 1 and a = 4 * 2 = 8
third iteration, n = 1 - 1 = 0 since n = 0 then it stops.

javascript recursive with parameters to decrement

hello I'm new learning recursive but i don't know to solve with this problem,
cause this one using 2 parameters, I don't know how to return with 2 arguments.
this is the normal loop ,not a recursive yet cause i dunno how to change it to recursive:
function deret2(num,num2){
var tampung = 1;
for (var i= num; i >= 1 ; i-= num2){
tampung = tampung * i ;
}
console.log(tampung);
}
deret2(12,5); //12* 7 * 2 = 168
Edit : the recursive I made :
function deret(num,num2) {
//var tampung = 1;
if (num <= 0) { // terminal case
return 1;
} else
{ // block to execute
return num * deret(num-num2,num2);
}
};
deret(12,5);
it won't work cause number* deret(2 arguments here) ?? that's why i don't know how to make this a recursive with 2 parameters, how could u save it and multiply it against 2 arguments ?
You could use a recursive function with check.
You need for a recursive function a check if the recursion should stop, or if the function should call again with same or changed paramters. Then you need a value to return in both cases.
Rule of thumb, for multiplications return as last value 1 and for addition 0.
num num2 return
--- ---- ------------------
12 5 12 * deret2(7, 5)
7 5 7 * deret2(2, 5)
2 5 2 * deret2(-3, 5)
-3 5 1
function deret2(num, num2) {
return num >= 1 ? num * deret2(num - num2, num2) : 1;
}
console.log(deret2(12, 5)); //12* 7 * 2 = 168
With if syntax.
function deret2(num, num2) {
if (num >= 1) {
return num * deret2(num - num2, num2);
} else {
return 1;
}
}
console.log(deret2(12, 5)); //12* 7 * 2 = 168
Bonus: The shortest version.
function deret2(num, num2) {
return +(num < 1) || num * deret2(num - num2, num2);
}
console.log(deret2(12, 5)); //12* 7 * 2 = 168
A recursive function calls itself, and with an extra parameter, we don't need to keep track of a mutating variable. Looping and recursion are very closely related, to the point where the transformation is mechanical.
function deret2(num,num2,tampung){
if (num >= 1) {
deret2(num - num2, num2, tampung * num);
} else {
console.log(tampung);
}
}
deret2(12,5,1); //12* 7 * 2 = 168
Note that we're passing in the initial value of tampung directly now, instead of encoding it into the recursion. If you don't want the caller to pass the base value of tampung, it's fairly common to make a helper function to encode that base case and then start the recursion.
A recursive function should have itself declared inside the function AND a stop if condition:
function deret2(startNumber,step){
if(startNumber>= 1){
return startNumber * deret2(startNumber - step, step);
}else{
return 1;
}
}
deret2(12,5); //12* 7 * 2 = 168

Categories

Resources