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

What is the difference between yours and my ways of getting this task done? Esp I'm interested in the random line.

This is my code:

var firstNum = parseInt(prompt('Type first number'));
var secondNum = parseInt(prompt('Type second number'));
var dieRoll = Math.floor(Math.random() * secondNum) + firstNum;
document.write('<h2>Your random number from ' + firstNum + ' to ' + secondNum +' is ' + dieRoll);

Should I use your variant of formula in code or mine is fine, too?

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

Cause my program works completely fine. Is there any use to change mine variant to yours? I thought that +1(firstNum) outside bracket is like max and *secondsNum is like min.

Phillip Kerman
Phillip Kerman
Courses Plus Student 285 Points

The +1 is because Math.random() is a number between 0 and 1 (but not including 1)... so the highest is 0.9999..

I'm not so sure your code works though--you want a number between the first and second number right? So, if you want a number between 2 and 4, your code says "get a random number from 0 to less than 4, and add it to 3". What if your random is 3? Then it's 3+3 (but 6 is higher than your high number).

The basic solution is "take my low number, add a random number from 0 to the difference between high and low".

Forgive me if I didn't understand the question.

Hi. Please markdown your code: https://teamtreehouse.com/library/code

Done.

1 Answer

Steven Parker
Steven Parker
231,269 Points

The formula for producing a random number between two (inclusive) limits is: random * range + minimum, where "range" is one more than the difference between the two limits. As Phillip pointed out, the operations perfomed by the code shown will potentially produce number larger than the upper limit.

Also, be careful with the placement of parentheses, otherwise the math will be done based on operator precedence, which in this case means the multiply will be done before the addition or subtraction and also throw off the results.