How to Create a Random Number Generator in C++
Introduction
In this article, we’ll go over the functions needed to create a random number generator in C++. Random numbers are essential in computing to introduce anonymity and security. A random number generator forms the backbone of creating pseudo-random numbers.
The idea behind pseudo-random numbers is that a computer does not have a thinking process to select a random number. Even though the output may seem random, the values are mathematically computed.
srand() and rand() Functions
The srand()
function in C++ can perform pseudo-random number calculations. This function requires a seed value which forms the basis of computation of random numbers.
srand(unsigned int seed_value)
With the help of the seed value, srand()
sets the stage for the generation of pseudo-random numbers by the rand()
function:
int random = rand();
And voilà! You have generated a random number. However, understanding the concept behind random number generators is crucial.
Importance of a Seed Value
The seed value determines the sequence of random numbers. If the same seed value is provided, the set of numbers will be identical. Without a fresh seed, the output remains constant across program runs.
To address this, use the current timestamp as a fresh seed value:
time_t current_time = time(NULL);
srand((unsigned) time(NULL));
Create the Perfect Random Number Generator in C++
Below is an example of generating a random number:
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
srand((unsigned) time(NULL));
int random = rand();
cout<<random<<endl;
return 1;
}
Output:
1897776064
Generate Random Numbers Within a Range
To restrict random numbers to a specific range, use the modulus operator %
:
int random = rand() % 10;
To generate random numbers between 1 and 9:
int random = 1 + (rand() % 9);
General formula:
int random = offset + (rand() % range);
Example program generating 5 random numbers between 100 and 200:
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
srand((unsigned) time(NULL));
for(int i=1; i<=5; i++){
int random = 100 + (rand() % 101);
cout<<random<<endl;
}
return 1;
}
Output:
144
175
162
137
200
Applications of Random Number Generators (RNGs)
- Cryptography: Unpredictability is key in security, making RNGs vital for keys and nonces.
- Games: Randomness, like dice rolls or card shuffles, adds fun and uncertainty.
- Randomized Algorithms: Adding randomness can improve algorithm performance and outcomes.
Conclusion
The RNGs or PRNGs (Pseudo-Random Number Generators) are foundational for modern cybersecurity and cryptography. They generate numbers that appear random through mathematical computation. We hope this article was helpful. Feel free to comment below for questions or suggestions.