Understanding the math (steps)

Greetings!
If anyone can help please do :slight_smile:
I am now in the functions chapter of eloquent JavaScript. I am understanding the components of functions however the math is giving me some trouble.
I was experimenting with a concept to see how it works so I wrote this small piece of code…

function range(x) {
if (x >= 10) return 0;
return x + range(x*2);
}
range(1);

The solution comes out to 15

if I plug in range(2):

function range(x) {
if (x >= 10) return 0;
return x + range(x*2);
}
range(2);

The solution returns 14

I cant for the life of me figure out the steps of he math. How it actually stacks up step by step to come to the answers. I know if I understood one I would understand the other. Hope what I am asking for help with is clear. Thanks in advance to anyone who can provide some clarity.

Hey @jayharden1, hope you are well.

First, is not good practice to call the same function within its logic, it can lead into infinite loops or unexpected results.

So lets analyze it:
FOR range(1)

IF x is greater than 10, return 0,
else, it will return x + (x*2) (calling the function again.

the value for `return x + range(x*2):
it will run into a nested function that will go into steps like this until one of the nested iteration is higher than 10.

image

If you sum all the x values, the result is 15.

Hope this helps
Carlos Z

1 Like

Greetings Carlos!
Thank you so much! I realize now the completely simple mistake I was making.
Thanks for the tip, it was a mistake on my part in writing it out like that, but I also I did not know that it could perhaps lead to infinite loop at some point.

all the best…
Jason

1 Like