Back to Browse

Random numbers in a range in C code - optimized for speed

26.6K views
Mar 16, 2025
9:24

Learn how to generate random integers between two numbers (for example to roll dice) in C code. I describe optimizations such as using multiplication instead of modulo and calling bulk random data APIs. I also discuss "modulo bias" and cryptographically secure pseudorandom number generators. APIs discussed: arc4random(), arc4random_uniform(), arc4random_buf(), getrandom(), rand(), random(), /dev/urandom Links for further research: Daniel Lemire paper on divisionless random number generation - https://arxiv.org/abs/1805.10941 Lemire blog post - https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ Swift algorithm - https://github.com/swiftlang/swift/pull/39143 (got this wrong in the video - it didn't actually get merged) Pandemic board game - https://amzn.to/462zij1 As an Amazon Associate I earn from qualifying purchases.

Download

1 formats

Video Formats

360pmp412.2 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

Random numbers in a range in C code - optimized for speed | NatokHD