How rand() function works in a program.Pease explain anyone | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How rand() function works in a program.Pease explain anyone

working of rand function

28th Nov 2017, 4:29 PM
Suraj Satankar
Suraj Satankar - avatar
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 :)
28th Nov 2017, 5:22 PM
Dennis
Dennis - avatar
0
thanks @Dennis for the answer i understand a lot aboit rand function
28th Nov 2017, 5:58 PM
Suraj Satankar
Suraj Satankar - avatar