I am writing a c++ library for very large integers. (very large meaning hundreds of digits or more).
I want to add a function
$Y = \operatorname{randBig}(X)$
to generate a very large, uniformly distributed pseudo-random integer $Y \in [0, X]$.
I have at my disposal a function
$y = \operatorname{rand}(x)$
that generates uniformly distributed pseudo-random integers $y \in [0, x]$.
But the largest allowed value for $x$, called $x_{max}$, is way less than $X$:
$x_{max} \lll X$
My first attempt:
To generate the random number $Y \in [0, X]$:
- Assume X to be in base $b = x_{max} + 1$
- Generate all digits of $Y$ using $Y_i = \operatorname{rand}(X_i)$ (where $X_i$, $Y_i$ are the i-th digit of $X$ and $Y$ respectively).
This doesn't work: e.g. when $x_{max} = 9$ then randBig(100) would always return either 0 or 100, but nothing else.
My second attempt:
To generate the random number $Y \in [0, X]$:
- Assume X to be in base $b = x_{max} + 1$
- Generate all digits of $Y$ using $Y_i = \operatorname{rand}(x_{max})$ such that $Y$ has as many digits as $X$ (where $Y_i$ is the i-th digit of $Y$).
- If $Y \le X$ then return $Y$, otherwise go back to step 1.
This does work, but gets very slow very quickly for large bases.
My Question
Are there faster algorithms?