javascript recursive with parameters to decrement - javascript

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

Related

Looking for explanation of Greatest Common Divisor Recursive Function [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 last month.
Improve this question
I'm studying recursive functions, and one I came across is the greatest common divisor. I was working through a very long and complicated piece of code that was going nowhere, and when I looked up the solution, I see it's super short:
function gcd(num1, num2) {
if (num2 === 0) {
return num1;
}
return gcd (num2, num1 % num2);
}
I'm struggling to wrap my brain around how this works in the recursive return function call. Num2 becomes the first parameter for some reason, and how does the second parameter work? Is num1 % num2 the new value of num1? How is num2 going to get to 0? I don't see how it's value changes.
I'm struggling to wrap my brain around how this works in the recursive return function call. Num2 becomes the first parameter for some reason, and how does the second parameter work? Is num1 % num2 the new value of num1? How is num2 going to get to 0? I don't see how it's value changes.
num2 becomes the first argument to a new function call. We're not changing the value of the num1 we have, but telling JS that in the next call, the first parameter will get the value from what's currently in num2. Similarly, we calculate the next value of the second parameter as num1 % num2. (To understand how the math works, you might read up on the Euclidean algorithm, but the basic point is that for positive integers a and b, gcd (a, b) is precisely the same as gcd (b, a % b).)
So now we have two new numbers to test, and we call gcd with these two numbers, and, crucially, when that function returns, we return its result as our own:
return gcd (num2, num1 % num2);
//^^^^^^
This process stops when num2 is zero. Then we can simply return num1.
We can add some logging to your function, using an additional parameter, depth to track the recursion depth, initializing it at first to 0. That could give us output like this:
in gcd (120, 42)
num2 <> 0
value of num1 for the next call is num2: 42
calculating value of num2 for next call: num1 % num2: 120 % 42 ==> 36
calling gcd (42, 36)
in gcd (42, 36)
num2 <> 0
value of num1 for the next call is num2: 36
calculating value of num2 for next call: num1 % num2: 42 % 36 ==> 6
calling gcd (36, 6)
in gcd (36, 6)
num2 <> 0
value of num1 for the next call is num2: 6
calculating value of num2 for next call: num1 % num2: 36 % 6 ==> 0
calling gcd (6, 0)
in gcd (6, 0)
num2 == 0
returning 6
returning 6
returning 6
returning 6
which you can see by expanding and running this snippet:
const log = (depth, s) => console .log (' ' .repeat (depth) + s)
function gcd (num1, num2, depth = 0) {
log (depth, `in gcd (${num1}, ${num2})`)
if (num2 === 0) {
log (depth, `num2 == 0`)
log (depth, `returning ${num1}`)
return num1
}
log (depth, `num2 <> 0`)
log (depth, `value of num1 for the next call is num2: ${num2}`)
log (depth, `calculating value of num2 for next call: num1 % num2: ${num1} % ${num2} ==> ${num1 % num2}`)
log (depth, `calling gcd (${num2}, ${num1 % num2})`)
const result = gcd (num2, num1 % num2, depth + 1)
log (depth, `returning ${result}`)
return result
}
console .log (gcd (120, 42))
.as-console-wrapper {max-height: 100% !important; top: 0}
It might be tricky to understand without going through examples with pen and paper. num1 % num2 becomes the new value of num1 for each recurring call of the function.
If you try it with gcd(14,4),
4 != 0, 14 % 4 = 2 then next call is gcd(4, 2).
2 != 0, 4 % 2 = 0 then next call is gcd(2, 0).
0 == 0 then greatest common divisor of 14 and 4 is 2. This value is returned all the way up the call stack.
Another example with gcd(5,3):
3 != 0, 5 % 3 = 1 then next call is gcd(3,1).
1 != 0, 3 % 1 = 0 then next call is gcd(1, 0).
0 == 0 then greatest common divisor of 5 and 3 is 1.
An exact equivalent but more clear (to me) code is:
function gcd(num1, num2) {
if (num2 === 0) return num1;
else return gcd (num2, num1 % num2);
}
Now do a few by hand:
console.log(gcd(15, 6));
num2 (6) is not 0 so return gcd(6, 15%6) or gcd(6,3)
num2 (3) is not 0 so return gcd(3, 6%3) or gcd(3,0)
num2 (0) is now 0 so return 3
console.log(gcd(6, 15));
num2 (15) is not 0 so return gcd(15, 6%15) or gcd(15,6)
num2 (6) is not 0 so return gcd(6, 15%6) or gcd(6,3)
num2 (3) is not 0 so return gcd(3, 6%3) or gcd(3,0)
num2 (0) is now 0 so return 3
Or, you can let the code tell you what's going on:
This is for factorial(n) but you could do the same for gcd():
The important point is that "k" is different for each call:
console.log("FINALLY, factorial(5) = ", factorial(5));
function FACTORIAL(num) { // this is without the BS
if (num == 1) return 1;
else return num * factorial(num-1);
}
function factorial(num) { // this shows all
console.log("getting factorial(" + num + ")");
if (num == 1) {
console.log("factorial of 1 is just 1");
return 1;
} else {
console.log("need to get factorial(" + (num-1) + ")");
let k = num * factorial(num - 1);
console.log("got factorial(" + num + ") = " + k);
return k;
}
}

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.

i wanna solve using recursive function.. but can't solve it

function test3(num) {
value = value * Number(str[i]);
let value = 1;
let str = String(num);
for (let i = 0; i < str.length; i++) {
if (str.length <= 1) {
}
return test3(value);
}
return value;
}
i wanna make single Digits using recursive function.
but, the code's value can't access..
i m searching in google about recursive fuction, it's not good answer..
why cant access 'value' ?
i wanna make
234,
2* 3* 4
2* 4
8
786,
7 * 8 * 6 -> 336
3 * 3 * 6 -> 54
5 * 4 -> 20
2 * 0 -> 0
like that. i want to know why can't access 'value' in the function.
thank you.
You can't access variables form the parent function's scope. If you want to access variables, pass them in as a parameter. Regardless, this is much easier done without strings:
function productOfDigits(num) {
if (num < 10) {
return num;
}
return (num % 10) * productOfDigits(Math.floor(num / 10));
}
// use this one
function repeatedProductOfDigits(num) {
if (num < 10) {
return num;
}
// multiply all the digits then try again
return repeatedProductOfDigits(productOfDigits(num));
}
num % 10 gets the last digit, and Math.floor(num / 10) gets every digit except the last, so productOfDigits(786) == 6 * productOfDigits(78) == 6 * 8 * productOfDigits(7) == 6 * 8 * 7.
It looks like you are trying to calculate the multiplicative digital root -
const multRoot = n =>
n < 10
? n
: multRoot(product(digits(n)))
const digits = n =>
n < 10
? [ n ]
: [ ...digits(Math.floor(n / 10)), n % 10 ]
const product = ns =>
ns.reduce(mult, 1)
const mult = (m, n) =>
m * n
console.log(multRoot(234)) // 8
console.log(multRoot(786)) // 0
To see a variant of this problem, read this Q&A.

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 Function that validates exponent equations

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!

Categories

Resources