Tuesday, November 24, 2009

Using the gmp library to do prime factorisation

This is slow, the only attempt at optimisation is attempting division with odds only. I use this for large numbers (>2^64), keeping a bit array of primes for testing wouldn't fit.


void get_prime_factors(mpz_t in) {
mpz_t n,q,upper;

mpz_init(n); mpz_init(q); mpz_init(upper);

mpz_set(n,in);

gmp_printf("%Zd=",n);

mpz_set_ui(q,2);
while (mpz_divisible_p(n,q)) {
gmp_printf("%Zd ",q);
fflush(stdout);
mpz_divexact(n,n,q);
}

mpz_set_ui(q,3);
mpz_sqrt(upper,n);
while (mpz_cmp_ui(n,1) != 0 && mpz_cmp(q,upper) <= 0) {
while (mpz_divisible_p(n,q)) {
gmp_printf("%Zd ",q);
fflush(stdout);
mpz_divexact(n,n,q);
mpz_sqrt(upper,n);
}
mpz_add_ui(q,q,2);
}

if (mpz_cmp_ui(n,1) != 0) {
gmp_printf("%Zd ",n);
}

gmp_printf("\r\n");

return;
}

No comments: