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

Blake Piper
Blake Piper
1,223 Points

Question about this equation and negative numbers.

I have the a question to how the equation works. it seems to not matter in which order the larger or smaller number are in the equation, and i was trying to figure out why this is. do negative integers not show up in the final variable? this is my code which seems to work fine, whether or not the user enters a larger number first or second. all that is changed is the order on which the numbers in document.write are placed so that it looks funny. ie: 14 is a number between 55 and 2.

var userNumber1 = prompt(' Enter a number' );

var userNumber = prompt( ' Enter a number' ) ;

var topNumber = parseInt(userNumber);

var topNumber1 = parseInt(userNumber1);

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

document.write( randomNumber + ' is a number between ' + topNumber1 + ' and ' + topNumber);

1 Answer

Steven Parker
Steven Parker
231,269 Points

It might seem like it works the same either way, but if you did a really large number of samples and analyzed the results you'd notice that there's a difference in number range. When you put the limits in lowest first, the output can be any number from the lowest to the highest, including both limits, and the chances of getting each number are essentially the same (the distribution is even).

But if you reverse the order, you will never get the lowest number, and the chances of getting the highest one will be extremely remote compared to the others.