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

JavaScript JavaScript Numbers The Math Object Random Number Challenge – Two Numbers Solution

Keith Griffin
Keith Griffin
4,833 Points

How are we supposed to figure out the the equation Math.floor(Math.random() *(highNumber - lowNumber) + lowNumber?

The equation makes sense to me after the fact. For example. (Math.floor(.5) *(10-5) +5) = Math.floor(2.5+5) = 7 which is between 10 and 5 but I don't understand how to come to the conclusion to subtract the low number from the high number.

2 Answers

Steven Parker
Steven Parker
231,268 Points

This formula isn't quite right. The multiplier should be highNumber - lowNumber + 1, which represents the range of numbers you want. For example, if you wanted a number between 10 and 15, (15 - 10 + 1) gives you 6, which is how many numbers to choose from (10, 11, 12, 13, 14 and 15).

After multiplying (and applying "floor"), you'll have one of 6 values, but starting from 0. Adding in the low value again shifts the range back up into where you want it.

Frederik Dobbener
Frederik Dobbener
2,356 Points

This is a very good explanation and helped me understand it better. Thanks!

Loved this explanation on the formula, thanks!