M
M
Marik Zukor2016-02-14 21:05:03
JavaScript
Marik Zukor, 2016-02-14 21:05:03

How is x * func(x, n - 1) calculated (recursion)?

I almost don’t understand how recursion happens, how much I don’t read the material, everything is so abstract and not quite “logical”.

function func(x, n) {
  if (n != 1) { 
    return x * func(x, n - 1);
  } else {
    return x;
  }
}

alert(func(4, 3));

Is that why this code returns 64? it's not a cycle! the check should go once if (n != 1) , but for some reason it's different here. But that's okay. How is the expression x * func(x, n - 1) evaluated ? After all, if you substitute 4 and 3, you get 4 * func(4, 3 - 1) . And this in turn is 4 * func(4, 2) . And how is the multiplication of 4 by func(4,2)? what is multiplied by what? what does the function return before multiplication and why is it so? Thanks for understanding! Hope I get it

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
timfcsm, 2016-02-14
@BeriaFantom

first pass: 3!=1 => 4 * (func(4, 3-1))
second pass: 2!=1 => 4 * (func(4, 1))
third pass: 1==1 => return 4
in the second pass substitute 4 => 4*4 = 16, return 16
in the first pass substitute 16 => 4 * 16 = 64

A
Askar Mukhametshin, 2016-02-14
@Maskazan

We break it down into steps (to understand how recursion works on a machine, you need to take into account the work of call stacks ):

  1. [stack level 0] Call func(4, 3)
  2. [stack level 1] n == 1 ? Not
  3. [stack level 1] Call func(4, 2)
  4. [stack level 2] n == 1 ? Not
  5. [stack level 2] Call func(4, 1)
  6. [stack level 3] n == 1 ? Yes
  7. [stack level 3] Return X value equal to 4
  8. [stack level 2] Return the value of expression X multiplied by the returned value (4 * 4) which is 16
  9. [stack level 1] Return the value of expression X multiplied by the returned value (4 * 16), which is 64
  10. [stack level 0] Get 64

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question