"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does `rand() % 14` return a finite value on Apple MCG?

Why does `rand() % 14` return a finite value on Apple MCG?

Posted on 2025-04-14
Browse:219

Why Does `rand() % 14` Return Limited Values on Apple\'s MCG?

Rand() % 14 Generator Returns Limited Values

In a recent program, a developer encountered a problem where the rand() % 14 expression consistently produced values of only 6 or 13. Despite attempting to execute the code multiple times, the results remained consistent. The problem lies in the nature of the random number generator used by Apple's MCG.

As explained by Wikipedia, the MCG's multiplier of 16807 is divisible by 7. This means that the first random number generated after srand() will have only one bit of entropy when taken modulo 14, resulting in the limited range of values. This deficiency is attributed to the low-quality random number generator used by Apple.

A simple solution to this issue is to invoke rand() several times after srand() and discard the initial results. This will enhance the entropy of the generated numbers and resolve the issue of limited value output.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3