Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Ivana Lescesen
Ivana Lescesen
19,442 Points

I do not understand the math? Thanks for your help

Can someone explain this math:

var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumber + 1)) + bottomNumber;


3 Answers

First, you find the difference of the range of the numbers, and then +1. So, for the 10-25 example, 25 - 10 = 15. 15 + 1 = 16. Right now, we have Math.floor(Math.random() * 16). For that expression only, you'll get a random number from 1-15. 16 is exclusive. Then, you add the bottom number, and in this case, it would be 10. The math.floor runs first, and as you know, you can get 15 from just the math.floor expression, so if you add 10 (bottom number), there's the possibility to get the max number 25. If you get 1 for the math.floor expression and add 10, you can get the minimum of 10. I hope this makes sense.

Ivana Lescesen
Ivana Lescesen
19,442 Points

Why do we add +1 ? If we get 1 + 10 would not that be eleven?

is this as same var dieRoll = Math.floor( Math.random() * (6 -1 +1) ) +1;

as this var dieRoll = Math.floor( Math.random() * 6) +1;

+1 because of Math.floor. It rounds down. So if you want a number between 1-10, you need to +1 after the Math.floor, otherwise it would be 1-9. Consider this: Math.floor(Math.random() * 10); That expression is for 1-9. You need to +1 to make it, so you can get 10. Those examples you presented are indeed the same.