user2500161 user2500161 - 5 years ago 521
Javascript Question

Javascript recursive

i have this problem i want to create a recursive function for calculate all possibilities to have a number (k>0), with the addition of number 1 or 2. Example for the number 2 i have two poss. 2 = 1+1 and 2 = 2 , for number 3 two poss. 3 = 1+1+1 or 3 = 1+2. I have this idea, but doesn't work ..

function op(k, n, i) {
if (n == k) {
return i++;
} else if (n > k) {
return i;
} else {
n = n + 1;
op(k, n, i);
n = n + 2;
op(k, n, i);
}
}

op(3, 0, 0);

Answer Source

Not sure why you are looking to do this recursively. More explanation would have helped from that angle. If you are trying to get back the number of times a value k can be added using 1's and 2's, then simply take the base case (1+1+1+...k times), and add the specific case where 1's are grouped (1+1+1+(1+1)) and that is your answer.

function op(k){
 return 1 + parseInt(k/2,10);
}
for(var i = 1;i < 100; i++){ console.log(i+": "+op(i)); }

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