Search code examples
c++ntl

Generate a random number of type NTL::ZZ in C++


I know that NTL::RandomBnd(NTL::ZZ &x, const NTL::ZZ &n) will make a random number that less than n, and assign it to x.
But I want to implement a function NTL::ZZ generate_random_number(NTL::ZZ a, NTL::ZZ b) which returns a value that in range [a,b]
This is my code to implement the function

NTL::ZZ generate_random_number(NTL::ZZ a, NTL::ZZ b)
{
    NTL::ZZ random_number = a;
    while(random_number < a)
        NTL::RandomBnd(random_number, b);
    return random_number;
}

When a is close to b, this function won't work fine.

Is there a way to optimize it or any other function to implement the function I need.
Sorry for my poor English and don't care about the end points of [a,b]


Solution

  • You are on the right track, but the function can still be optimized to work better. One way to do this is reject sampling:

    NTL::ZZ generate_random_number(const NTL::ZZ &a, const NTL::ZZ &b)
    {
        NTL::ZZ range = b - a + 1;  // Compute the range of the interval [a, b]
        NTL::ZZ random_number;
    
        do {
            random_number = a + NTL::RandomBnd(range);  // Generate a random number in the range [0, range-1] and add it to 'a'
        } while (random_number > b);  // Reject the random number if it's greater than 'b'
    
        return random_number;
    }
    

    This should make the function run a lot better, hope it helped!