# Random whole number between two integers JavaScript

In the given problem statement, we have to find the whole number between two integers with the help of Javascript functionalities. So for doing this task we can use some in-built functions of javascript and also for loop to get the required result.

## Understanding the problem statement

The problem statement is to write a function in Javascript that will help to find out the whole random number between two integer numbers. For example if we want to print a random number between 1 to 5 so there are 5 possibilities, the number can be 1, 2, 3, 4, 5. So from 1 to 5 any random number can be printed as the output.

## Logic for the given problem

To create a function to get a random number from the given two integer numbers can be found out with the help of Math.random function in Javascript. This function generates a random decimal number. So we will solve this problem in two ways.

In the first method we will generate a random decimal number between 0 and 1. And then multiplies this decimal by the difference between max and min values. And add min and rounds down to the nearest whole number with the help of Math.floor method.

## Algorithm

Step 1 − Declare a function called getRandomInt which is using two parameters of minimum and maximum of integer numbers.

Step 2 − Inside this function we will use the Math.random method to generate a random decimal between 0 and 1.

Step 3 − Then multiply this decimal with the difference of max and min -1. Then add min in the difference.

Step 4 − Rounds down to the nearest whole number with the help of Math.floor function.

## Code for the algorithm

//Function to get the random number between min and max
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(getRandomInt(10, 20));


## Complexity

The time complexity for the above functions are O(1). Because the loop iterates through once for every integer between the two numbers. And the space complexity for the function is constant O(1). Because it only requires a few variables to store the result and the loop counter.

## Conclusion

As we have seen above we can find a random number by many ways. We have used a predefined function of Javascript to get the random number between the given range.

Updated on: 18-May-2023

89 Views