0

In the book I'm studying we are given a function to make rand() work for numbers that are smaller that RAND_MAX

```
int nrand(int n){
if(n <= 0 || n > RAND_MAX)
throw domain_error("Argument to nrand is out-of-range");
const int bucket_size = RAND_MAX/n;
int r;
do r = rand()/bucket_size;
while(r >= n);
return r;
}
```

and then we are asked to 'adapt' it so it'll work for numbers that are larger than RAND_MAX

I was offered this solution

```
if(n > RAND_MAX){
return nrand(n % RAND_MAX) + RAND_MAX * nrand(n / RAND_MAX);
```

which seemed good to me ... but I realized it won't work for a number that's exactly 2,3,4 ... times bigger than RAND_MAX ... cuz it'll pass a 0 value no nrand, causing it to throw and exception and fail ... so I came up with this simpler solution

```
if(n > RAND_MAX){
int r = rand();
return r + nrand(n - r);
}
```

it works ... BUT since I'm using + to create the final number ... larger numbers will happen more ofter than smaller numbers ... like the chances of getting 0 or 1 (for example) will be really small!

Can anyone help me think of a better solution?