Dell Watson - 1 year ago 69
Javascript Question

# 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  12 * 7 * deret2(2, 5)
2     5  12 * 7 * 2 * deret2(-3, 5)
-3     5  12 * 7 * 2 * 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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download