Home  >  Article  >  Backend Development  >  Why Does `rand() % 14` Sometimes Only Return 6 or 13?

Why Does `rand() % 14` Sometimes Only Return 6 or 13?

DDD
DDDOriginal
2024-11-25 10:34:11328browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn