skip to Main Content

I am having a brain lapse in recursion and trying to get the math right. The function gives me what I want but my brain does not.

let recurseSum = (x, n) => {
    if(n === 1){ return x}

    return x + recurseSum(x, n-1)
}

log = console.log
log(recurseSum(3, 2))

How is this broken down again, the answer and what I write is not right.

3 + recurse(3, (2-1) = 3 + 1 = 4
3 + resurse(3, (1-1) = 3....ggrrrrrrr

How do I write this out properly.

2

Answers


  1. Chosen as BEST ANSWER

    Per the comments I have answered my own question

    3 + recurseSum(3, 3-1)
    3 + recurseSum(3, 2-1)
    n === 1 returned
    
    
    Bubbles back up 3 + 3 = 6
    
    For some reason i was trying to add:
    3 + 3, (3-1) = 6 couter = 2
    6 + 3, (2-1) = 9 counter = 1 return
    x = 0; for a new person recursion is tough.
    

  2. Just add some logging to see how it actually behaves, no need to type this stuff out manually

    let recurseSum = (x, n) => {
      let val;
      if(n === 1){
        val = x;
      } else {
        val = x + recurseSum(x, n-1);
      }
      console.log(`recurseSum(${x}, ${n}) = ${val}`)
      return val
    }
    
    console.log('Final Value: ', recurseSum(3, 2))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search