Home > Article > Backend Development > Why Does `rand() % 14` Sometimes Only Return 6 or 13?
Rand() % 14: Uncovering the Mystery of Repeating Values
In programming, the rand() function is commonly employed to generate random numbers. However, some users have encountered an intriguing issue where the expression rand() % 14 consistently produces only 6 or 13.
To understand this behavior, let's delve into the workings of rand(). It utilizes Apple's Mersenne Congruential Generator (MCG) algorithm, which involves a specific multiplier. Unfortunately, this multiplier is divisible by 7, resulting in erratic behavior when generating random numbers within a limited range.
Specifically, the first random number generated after calling srand() will exhibit only one bit of entropy modulo 14. This means it can assume only two possible values: 6 or 13.
To work around this issue, there's a simple solution. Simply call rand() a few times and discard the results to introduce randomness. This ensures that the first random number used in rand() % 14 is not influenced by the initial seeding.
The above is the detailed content of Why Does `rand() % 14` Sometimes Only Return 6 or 13?. For more information, please follow other related articles on the PHP Chinese website!