JoshW
JoshW

Reputation: 105

How to use MPIR Prime testers mpz_likely_prime_p and mpz_probable_prime_p?

I'm trying to use MPIR's prime tester(s) for rapid non-sequential testing; however, I'm new to MPIR and am confused about their usage - specifically the "gmp_randstate_t" parameter used by the function. Here's what I've got so far:

#include<iostream> // used for cout
#include<mpir.h>

int main() {
    mpz_t PrimeCanidate;
    mpz_init(PrimeCanidate);
    mpz_set_ui(PrimeCanidate, 3); // sets PrimeCanidate to unsigned int "3"

    if (mpz_likely_prime_p(PrimeCanidate) == 1) {
        std::cout << "Number is prime: " << std::endl;
    }
}

As I'm only using one parameter inside mpz_likely_prime_p, it doesn't work - I just don't know what it's looking for with the other parameters (state, div) as shown in the documentation (http://www.mpir.org/mpir-3.0.0.pdf pg. 42):

MPIR Documentation Pg.42

Would anybody by chance have a simple code that uses the prime-testing functions in MPIR? Thanks a ton.

Upvotes: 1

Views: 151

Answers (1)

JoshW
JoshW

Reputation: 105

After a bunch of tinkering, I figured out how to properly initialize the "state" and div" parameters for mpz_likely_prime_p. Here's an example calculating and printing primes between 1 and 100:

#include<iostream> // used for cout
#include<mpir.h>

int main() {

    mpz_t PrimeCanidate;
    mpz_init(PrimeCanidate);
    mpz_set_ui(PrimeCanidate, 2);

    mpz_t additor;
    mpz_init(additor);
    mpz_set_ui(additor, 1);

    gmp_randstate_t state;
    gmp_randinit_default(state);

    mpir_ui div = 0;
    
    int maxbase = 100;
    for (int base = 2; base < maxbase; base++) {
        mpz_add(PrimeCanidate, PrimeCanidate, additor); // repeatedly adds one to PrimeCanidate
        std::cout << "Tested Number: " << PrimeCanidate << std::endl;

        if (mpz_likely_prime_p(PrimeCanidate, state, div) == 1) {
            std::cout << PrimeCanidate << " is prime." << std::endl;
        }
    }
}

This is probably not optimal, but it works and might be a good place to start.

Upvotes: 1

Related Questions