Re: [RFC PATCH] random: add get_random_max() function

From: Jason A. Donenfeld
Date: Sun Mar 24 2019 - 16:48:06 EST


I generally use a slightly simpler algorithm in various different projects:

//[0, bound)
static unsigned long random_bounded(unsigned long bound)
{
unsigned long ret;
const unsigned long max_mod_bound = (1 + ~bound) % bound;

if (bound < 2)
return 0;
do
ret = random_integer();
while (ret < max_mod_bound);
return ret % bound;
}

//[min, max_plus_one)
static unsigned long random_range(unsigned long min, unsigned long max_plus_one)
{
return random_bounded(max_plus_one - min) + min;
}

Is the motivation behind using Lemire that you avoid the division (via
the modulo) in favor of a multiplication?