I am relatively inexperienced in using arithmetic libraries. I need to try and write some code that computes the greatest common denominator, using one of the functions in the MPIR
library. I found several methods, and I do not understand the way they define the variables. For example: with regards to:
void mpz_gcd (mpz_t rop, mpz_t op1, mpz_t op2)
I cannot understand the variables types and how to use them. Can anyone provide me with some simple code that clarifies this to me?
But can not understand the variables types.
If it's the variable types you're concerned with, the mpz
one are simply arbitrary precision integers (as opposed to reals).
In terms of the variables themselves, rop
is the return variable, the one that will be set to the GCD of op1
and op2
.
For example, here's a complete program that illustrates the use of that function:
#include <stdio.h>
#include <mpir.h>
int main (void) {
mpz_t a, b, c;
mpz_init (a); mpz_init (b); mpz_init (c);
mpz_set_str (a, "1024", 10);
mpz_set_str (b, "768", 10);
mpz_gcd (c, a, b);
printf ("GCD of "); mpz_out_str (stdout, 10, a);
printf (" and "); mpz_out_str (stdout, 10, b);
printf (" is "); mpz_out_str (stdout, 10, c);
putchar ('\n');
return 0;
}
The output is:
GCD of 1024 and 768 is 256
I want to generate random values of long bits.
However, if (as you mention in a comment, though it's hard to see the applicability to GCD calculation) you desire a random number of 100 bits, you can use something like:
#include <stdio.h>
#include <time.h>
#include <mpir.h>
int main (void) {
mpz_t a;
gmp_randstate_t rstate;
mpz_init (a);
gmp_randinit_default (rstate);
gmp_randseed_ui (rstate, time (0));
mpz_urandomb (a, rstate, 100);
printf ("100 random bits gives: "); mpz_out_str (stdout, 10, a);
putchar ('\n');
return 0;
}