Using rand | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Using rand

How rand is used to get random numbers in specific range??? Very much confusion on this concept

3rd Jan 2018, 6:42 AM
Priyanka Thakur
Priyanka Thakur - avatar
2 Answers
+ 6
By default, rand() returns a number in the range 0 to RAND_MAX. The value of this constant value is quite large and varies according to numeric limits. Now, we can use rand to return a number in the range 0 to x-1, by doing : rand() % x; Now, If the range was 0 to RAND_MAX, the new range is 0 to x, as the modulo operation returns the remainder of a division by x, and every remainder will be less than x (and the range is x-1, as if the remainder is equal to x , it can still be divided to get a remainder 0.). Now, If you want a number in the range L to U, where L is the lower limit and U is the upper one, you do : L + (rand()%(U-L+1)); This is done as : >> 0 <= rand()%x <= x-1 // Default range for rand%x, where x // is the number to be found. >> L <= L+(rand()%(x)) <= L+x-1 // To increase the lower range, we simply // add L to the entire equation. >> L <= L+(rand()%(x)) <= U // Now, we assume that with the chosen // x, the range is L to U. So, L+x-1 = U => x = U-L+1. Thus, L <= L+(rand()%(U-L+1)) <= U And this way, rand returns a number in the range L to U.
3rd Jan 2018, 8:18 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 3
thx a lot Kinshuk 😊
3rd Jan 2018, 4:19 PM
Priyanka Thakur
Priyanka Thakur - avatar