![]() |
VOOZH | about |
Write a program that generates a random number within a specified range [L, R]. The program should take two integers, L and R, as input and output a random number between L and R (inclusive).
Examples:
Input: L = 10, R = 20
Output: 15Input: L = -5, R = 5
Output: 3
Approach: To solve the problem, follow the below idea:
We can generate a random number in the range [L, R] by finding how many numbers are there between L to R by the formula: diff = (R - L + 1). Now, we can generate a random number and modulo the random number by diff and add the remainder to L to get a random number between L to R.
Step-by-step algorithm:
Below is the implementation of the algorithm:
15
Time Complexity: O(1), as it takes constant time to generate a random number.
Auxiliary Space: O(1)