Why does the rand() generally returns 41 as its output everytime first when it is called? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why does the rand() generally returns 41 as its output everytime first when it is called?

I have seen 2 of the codes in the basic tutorials which has given 41 as output when the rand function is called for the first time in the program. Here I am giving a basic code where I found it...!!! int main() { cout << rand(); } Output: 41

2nd Jun 2019, 3:37 PM
Bhavya Sri Khandrika
Bhavya Sri Khandrika - avatar
6 Answers
+ 5
rand() function is not completely random. it performs a certain number of calculations to return the pseudo random value. this value is dependant on the previous value generated by the function. this is the reason why the numbers keep cycling upon multiple calls. the calculations are done on a certain seed (another number) and that seed is used for generating cycling sequences of pseudo random numbers. the seed is provide by the srand() function. if you change the seed to, for example, 7878 you wouldnt get 41 as the starting number. for generating more concise random numbers you have to pass a random seed each the program is run. this random seed is usually the machine time in ms. for eg this code would generate more concise random numbers. #include <iostream> #include <ctime> using namespace std; int main() { srand(time(0)); int x=10; while(x--) cout << rand() << endl; }
2nd Jun 2019, 3:46 PM
Farry
Farry - avatar
+ 5
As for why it is 41: The math for rand goes like this: seed = (214013 * seed + 2531011) % 2147483648; return seed / 65536; The default value for seed is 1 so (214013 * 1 + 2531011) % 2147483648 / 65536 = 41
2nd Jun 2019, 3:57 PM
Dennis
Dennis - avatar
+ 1
Sukruthi Pattabi They are the 3 constants, modulus ( m ), multiplier ( a ) and the increment ( c ) of a linear congruential generator. https://en.m.wikipedia.org/wiki/Linear_congruential_generator
13th Aug 2019, 8:12 AM
Dennis
Dennis - avatar
0
Pseudo-random algorithms
2nd Jun 2019, 6:02 PM
Werg Serium
Werg Serium - avatar
0
What are all those number ?! 214013 ? 2531011?2147483648? Can u please expain ? Dennis
13th Aug 2019, 6:47 AM
Sukruthi N S
Sukruthi N S - avatar
0
Thank you ☺ Dennis
14th Aug 2019, 4:41 AM
Sukruthi N S
Sukruthi N S - avatar