Generating Prime Numbers

A common reason to use a large-integer library is to implement public-key encryption, and the algorithms for such encryption often require large prime numbers.

With larger bit-sizes, the is_prime and random_prime functions can take a very long time to run, so you can pass an optional callback function to them as well. The provided callback function (which takes no parameters and returns a bool) will be called regularly during this time, and if it returns false, the function will abort and return zero (for random_prime) or -1 (for is_prime) instead of a value.

Here is an example of how to use the library functions to create a prime number of a specific length, using the system's strong random number generator:

#include <iostream>
#include <boost/xint/integer.hpp>

bool callback() {
    std::cout << '.' << std::flush;
    return true; // Return false to abort a long operation
}

int main() {
    using std::cout;
    using std::endl;
    using namespace boost;
    using namespace xint;

    const unsigned int bits = 512;

    try {
        // Use the system's strong random number generator, via the XInt-
        // provided convenience class.
        strong_random_generator gen;

        // Generate the prime number, keeping the user informed of the
        // progress.
        cout << "Generating...";
        integer p = integer::random_prime(gen, bits, callback);

        // Success!
        cout << "\nA random " << bits << "-bit prime is: " << p << endl;
    } catch (exceptions::no_strong_random& e) {
        // xint::strong_random_generator will throw this if the system doesn't
        // have a strong random number generator.
        cout << e.what() << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

(You can find it in the examples directory, by the name genprime.cpp.)


© Copyright Chad Nelson, 2010-2011. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)