VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-generate-a-random-number-between-l-to-r/

⇱ Program to generate a random number between L to R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to generate a random number between L to R

Last Updated : 18 Jan, 2024

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: 15

Input: 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:

  1. Find the difference between L to R by (R - L + 1).
  2. Now, generate a random number and modulo it by the above difference.
  3. Scale and shift the random number by adding the remainder to L to fit within the specified range [L, R].

Below is the implementation of the algorithm:


Output
15

Time Complexity: O(1), as it takes constant time to generate a random number.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: