Open In App

Program to generate a random number between L to R

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:




#include <cstdlib>
#include <ctime>
#include <iostream>
 
using namespace std;
 
int main()
{
    int L = 10, R = 20;
 
    srand(time(NULL));
    int random_number = L + rand() % (R - L + 1);
 
    cout << random_number << endl;
 
    return 0;
}




#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main()
{
    int L = 10, R = 20;
 
    srand(time(NULL));
    int random_number = L + rand() % (R - L + 1);
 
    printf("%d\n", random_number);
 
    return 0;
}




import java.util.Scanner;
 
public class RandomNumberGenerator {
    public static void main(String[] args) {
 
        int L = 10;
        int R = 20;
 
        int random_number = L + (int) (Math.random() * (R - L + 1));
 
        System.out.println(random_number);
    }
}




import random
 
L, R = 10, 20
random_number = random.randint(L, R)
 
print(random_number)




using System;
 
class Program
{
    static void Main()
    {
        int L = 10;
        int R = 20;
 
        Random rand = new Random();
        int random_number = rand.Next(L, R + 1);
 
        Console.WriteLine(random_number);
    }
}




let L = 10
let R = 20
 
let random_number = Math.floor(Math.random() * (R - L + 1)) + L;
 
console.log(random_number);

Output
15

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


Article Tags :