Skip to content
Related Articles

Related Articles

C++ program to generate random number
  • Difficulty Level : Hard
  • Last Updated : 03 Jan, 2018

The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function.

Prerequisite : random header in C++ | Set 1(Generators)

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to generate random number
#include <bits/stdc++.h>
using namespace std;
  
// Function with return random number from 1 to
// given limit
int randomNoGenerator(int limit)
{
    // uniformly-distributed integer random number
    // generator that produces non-deterministic
    // random numbers.
    random_device rd;
  
    // A Mersenne Twister pseudo-random generator
    // of 32-bit numbers with a state size of
    // 19937 bits.
    mt19937 gen(rd());
  
    // Uniform distribution
    uniform_int_distribution<> dis(1, limit);
    return dis(gen);
}
  
// Driver Code
int main()
{
    int limit = 100;
    cout << randomNoGenerator(limit) << endl;
    return 0;
}

chevron_right


Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :