Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 773
Dell Watson Avatar asked Sep 02 '25 03:09

Dell Watson


2 Answers

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
like image 112
Nina Scholz Avatar answered Sep 04 '25 17:09

Nina Scholz


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.

like image 24
Alejandro C. Avatar answered Sep 04 '25 18:09

Alejandro C.