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.
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.
So, a friend shared this code to me about factorials and I kind of am having a hard time understanding how it provides the correct result seeing that it didn't go through a loop. If someone could explain it to me like I'm 5 I'd really appreciate it.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
On the properties of the factorial, n! Can be written as n * (n-1) !.
That is, the result of the function for n can be obtained as n multiplied by the result of the function for n-1, and so on to 1 !:
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
The recursion basis is the value 1. And you could make the basis and 0. Then the code will be a little shorter:
function factorial(n) {
return n ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
In this case, the call factorial (1) is reduced to 1 * factorial (0), there will be an additional step of recursion.
The code is a recursive function call to get the factorial of a number.
function fact(n){ // function declaration
if(n === 1){ //strict type check if n is an integer 1 not a '1'
return 1; // return back 1
}else{ // if n is not 1
return n * fact(n - 1); //return the number n multiplied by the function call fact again in which the parameter is n-1 now.
};
};
console.log(fact(5)); //print the result of function call fact(5) and print it to console.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
It is a call which runs on the mathematical formula to calculate factorial:
n * (n-1) !
when it comes to recursion you can think of it as a function calling itself; in this case
function fact(n){
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
console.log(fact(5));
so in this case when you call fact(5)
you would get
5 * fact(5-1) = 4 * fact(4-1)= 3 * fact(3-1) = 2 * fact(2-1) = 1
resulting in 5 * 4 * 3 * 2 * 1 = 120
it's a bit tricky of a concept to figure out at first, try inserting a console.log into the function to give you a clearer picture of what's going on.
function fact(n){
console.log(n);
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
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 can't understand this recursion even though it's a really simple example. When it goes to power(base, exponent - 1); what is that supposed to do? How are things being multiplied when power keeps getting invoked until exponent equals 0?
function power(base, exponent) {
if (exponent === 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
Let's start from the beginning.
Let's say you call power(base, 0). Since exponent is 0, the function returns 1.
Now, let's say you call power(base, 1). Since exponent isn't 0 this time, the function calls power(base, exponent - 1) and multiplies it by base. (That's the key here...it takes the result from the recursive call, and adds its own twist.) Since exponent - 1 = 0, and power(base, 0) is 1, the result is effectively base * 1. Read: base.
Now on to power(base, 2). That ends up being base * power(base, 1). And power(base, 1) is base * power(base, 0). End result: base * (base * 1). Read: base squared.
And so on.
In case it wasn't obvious, by the way, this function will only work with non-negative integer exponents. If exponent is negative, or is even the tiniest bit more or less than a whole number, the function will run "forever". (In reality, you'll more than likely cause a stack overflow, once recursion eats up all of your stack.)
You could fix the function for negative powers with some code like
if (exponent < 0) return 1 / power(base, -exponent);
As for non-integers...there's no good way to solve that other than throwing an exception. Raising a number to a non-integer power makes sense, so you don't want to just truncate the exponent or otherwise pretend they didn't try to do it -- you'd end up returning the wrong answer.
This is similar to Math.pow(); it raises the base argument to the exponent argument.
For example, 2 ^ 4 is 16, so power(2, 4) would return 16. The if() statement checks to see whether the exponent (power) is zero and returns 1 if it is - any number raised to the power 0 equals 1.
The last line
return base * power(base, exponent - 1);
Is a recursive function that calls power() from within itself however many times specified by the value in exponent.
I'll try to explain recursion from the bottom up, or "from the middle" shall we say; it's probably easier to understand.
The bottom most call of power() takes 2 and 1 as it's arguments, and will return 1. This return value is then used in the second up call of power(), so this time the arguments passed are 2 and 2, which outputs 4, and so on until the top-most call to power() is passed 2 and 4 which returns 16.
Using a 2^3 example:
power(2, 3);
calls:
function power(2, 3) {
if (3 === 0) {
return 1;
} else {
return 2 * power(2, 2); //called
}
}
which leads to:
function power(2, 2) {
if (2 === 0) {
return 1;
} else {
return 2 * power(2, 1); //called
}
}
which leads to:
function power(2, 1) {
if (1 === 0) {
return 1;
} else {
return 2 * power(2, 0); //called
}
}
which leads to:
function power(2, 0) {
if (1 === 0) {
return 1; //returned
} else {
return 2 * power(2, -1);
}
}
which leads to:
function power(2, 1) {
if (1 === 0) {
return 1;
} else {
return 2 * 1; //returned
}
}
which leads to:
function power(2, 2) {
if (2 === 0) {
return 1;
} else {
return 2 * 2; //returned
}
}
which leads to:
function power(2, 3) {
if (3 === 0) {
return 1;
} else {
return 2 * 4; //returned
}
}
which ultimately returns 8, which is 2^3.
Assuming the initial call is power(10, 3)...
v-----first power() call returns base * (result of next power() call)
v-----second power() call returns base * (result of next power() call)
v-----third power() call returns base * (result of last power() call)
v------result of last power() call returns 1
(10 * (10 * (10 * (1))))
^-----return 1
^-----return base * 1 (10)
^-----return base * 10 (100)
^-----return base * 100 (1000)
Or go down the left, and up the right. Each line is a subsequent call to power() starting with power(10, 3)...
return base * power(base, 2); // return base * 100 (1000)
return base * power(base, 1); // return base * 10 (100)
return base * power(base, 0); // return base * 1 (10)
return 1; // return 1 (1)
base = 10
power = 3
10 * power(10,2)
10 * 10 * power(10,1)
10 * 10 * 10
maybe ok for positive integers...
Let's try to explain this with some maths.
f(x,y) = x^y # (1) function definition
= x * x * x * ... * x # (2) multiply x with itself y times
= x * (x * x * ... * x) # (3) rewrite using parentheses for clarity
= x * (x^(y-1)) # (4) replace the second part by (1) notation
= x * f(x, y-1) # (5) replace again by using f(x,y) notation according to (1)
f(x,0) = 1 # base case: x^0 = 1
Following this you can see that f(x,y) = x * f(x, y-1).
You can also see where
if (exponent === 0) {
return 1;
}
comes from, namely the base case that something to the 0th power always equals 1: f(x,0) = 1.
That's how this recursion was derived.
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.