0
How rand() function works in a program.Pease explain anyone
working of rand function
2 Answers
+ 3
C++'s rand function is a linear congruential generator.
https://en.wikipedia.org/wiki/Linear_congruential_generator
The following code generates the exact same sequence as C++'s rand when given the same seed.
#include <iostream>
#include <ctime>
namespace custom
{
unsigned seed = 0u;
void srand(unsigned seed_)
{
seed = seed_;
}
int rand()
{
seed = (214013 * seed + 2531011) % (1 << 31);
return seed / (1 << 16);
}
}
int main()
{
custom::srand( 6 );
for( int i = 0; i < 100; ++i )
{
std::cout << custom::rand() << std::endl;
}
}
Maybe if you see the actual function + the wikipedia link you might be able to figure out how it works :)
0
thanks @Dennis for the answer i understand a lot aboit rand function