Home > Software design >  Can someone gladly explain how this function works?
Can someone gladly explain how this function works?

Time:03-12

// I'm not sure how this works, I can assume It's a recursion which I'm having a hard time with. Please help :)

function a(b, c) {

  if(b > c) {
    a = 0; 
  } else {
    a = b   a(b * 2   1, c);
  }
  return a
}

console.log(a(1, 2018))

CodePudding user response:

Like is mentioned in the comment below your question, using a variable that is also the name of the function is not a good idea. So let's say:

function a(b, c) {
  console.log(b, c);
  if(b > c) {
    d = 0; 
  } else {
    d = b   a(b * 2   1, c);
  }
  return d;
}

console.log(a(1, 2018));

Until b is bigger than c, you are defining d in the else part of the statement. In that part of the statement, you are calling the function again, so your return has to execute the function again. When b gets bigger than c, the return can finally stop. It takes a while to get your head around recursion. Notice the console.log() that I have added, that should help your understanding a lot.

Since you are new, a few suggestions for better questions: make the title more descriptive so that other people may benefit from finding your question in search and also put more detail into the question about what parts you do and do not understand and what you have done so far to try to understand recursion, like is mentioned in another comment below your question.

CodePudding user response:

The function may not work properly because the function and a variable are both named a, but assuming it does:

if(b > c){
a = 0;
} //returns 0
else {
a = b   a(b * 2   1, c); // calculate a(b, c) where b = b * 2   1, adds b
}

The code prints 2036. Going through each step, we start with b = 1, c = 2018.

Then we plug them into a(b * 2 1, c) to get b = 3, c = 2018 (c will not change, so i will omit it.)

Then, b = 7, then 15, 31, 63, 127, 255, 511, 1023, 2047. At 2047, b > c so it will not return 2047 and instead return 0.

To get the answer, we sum up all the b's and the final a (0).

This gives 1 3 7 15 31 63 127 255 511 1023 2047 = 4083. However, we forgot to omit the 2047, so the actual answer is 1 3 7 15 31 63 127 255 511 1023 = 2036.

Edit: Technically, the summing and stuff happens backwards, although it won't change your answer.

I did try to use console.log in the middle of the function. It shows the answers added on backwards: 1023 ( 511), 1534 ( 255), 1789 (etc), 1916, 1979, 2010, 2025, 2032, 2035, 2036, 2036

  • Related