Math.floor(Math.random() * (max - min + 1)) + min;

Hey @Archana550 to understand this lets suppose our `max`

is 20 and `min`

is 10 `Math.random()`

generate a random number between 0 and 1. Which means they are all decimals like 0.23, 0.85, 0.33 etc… but this function never quite returns 1 so when a number is mutliplied to it like for example 10 then the random number is always between 0 and 9 (this function never quite returns 1) like if random number is 0.23 and mutiplied by 10 it makes 2.3 then `Math.floor()`

function which rounds off numbers can change it to 2,

0.85 x 10 is 8.5 i.e 8,

0.33x10 is 3.3 i.e. 3 etc…

now to generate a number between 10 and 20 we multiply `Math.random()`

with (max - min + 1) i.e. in our case (20 - 10 +1) which gives 11 which is basically 1 more than the range of our number if min and max were 15 and 30 it would have been (30 - 15+ 1) i.e. 16 We want 1 more than our range because Math.random will never quite get the last number as our output and we want to include all the number from 10 to 20 inlcuding 20.

So now `Math.floor( Math.random()*(max-min+1))`

will generate a number between 0 and 10 and round it off to nearest integer so the next step is to add min to this output to make this between 10 and 20. Lastly lets assume the random number generated is 0.75 to demonstrate this whole thing .

0.75 x (20 - 10 + 1 ) = 0.75 x 11 = 8.25

Rounding it off to 8

Our random number is 8.

to make it between our range lets add min to it i.e. 10

8+10 = 18

18 is our random number generated.

Math.random() returns a floating number between 0 and 1 (0 inclusive and 1 not).

So when we multiply this by some number, let’s say `5`

, the min value that we can get i 0, and max value is very close to 5, `4.99999`

.

`Math.floor()`

returns a the largest integer less than or equal to a given number. So when we use it with our number `4.999999`

we’ll get 4. But we’d like our function to include the `max`

number in the range.

So in this part `max - min + 1`

we add `1`

exactly because of that, so that we can get a random number that will include our `max`

.

Now we know this code can give us:

- the minimum value of
`0`

(when`Math.random()`

is`0`

) - and the maximum value of
`max - min`

, when`Math.random()`

is for example`0.9999`

```
Math.floor(Math.random() * (max - min + 1))
```

But we’d like to get a value that is greater than `min`

, so let’s add min at the end:

```
Math.floor(Math.random() * (max - min + 1)) + min
```

So if we add `min`

to our previous minimum and maximum value we’ll get:

- the minimum value =
`0 + min`

=`min`

- the maximum value =
`max - min + min`

=`max`