The task is …

to generate a random number between any two interger unsigned numbers. Let’s assume we’ve two numbers ‘a’ and ‘b’, where b > a. (I don’t count the case with b==a, cause it seems to be pretty strange!). The formula should be like that:

Math.random() * (b-a+1) + a

Looks very nice, but why is that?

because simply by using Math.random() * a gives a random between 0 and a-1. With the expresion (b-a+1) gives a random number between 0 and (b-a+1) and than by adding the value of a we’ve the number between a and b.

Related posts:

  1. How to detect a variable existence in JavaScript?
  2. Using rand() for a CAPTCHA!
  3. Browsers, pixels and graphic rendering!