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 Basics (Retired) Working With Numbers The Random Challenge Solution

Vic Mercier
Vic Mercier
3,276 Points

math.floor(math.random()*random1-random2+1)+random1;

I don't know why we add +random1 at the end of the syntax.

I believe that without the +random1 at the end, the number would be outside of the range.

Imagine is your numbers were 75 and 100. The difference is 25.

You would get something like .82929299 * 25 + 1

The result is not between 75 and 100. If you add 75 back in (ie, add random1), your number will be between 75 and 100.

1 Answer

Steven Parker
Steven Parker
231,007 Points

That's the way the formula for a random pick works.

The formula is: "(random * range) + minimum" where range is: "maximum - minimum + 1".

But that would mean your numbers are out of order, plus you need parentheses to override the operator precedence. So your code should probably be:

math.floor(math.random() * (random2 - random1 + 1)) + random1;