## MPIR Question C++

In this forum members can discuss topics about specific programming languages.
drwhat
Posts: 42
Joined: Tue Sep 06, 2011 4:56 am

### MPIR Question C++

I recently got MPIR installed and have been using it with Visual C++, specifically with the c++ wrapper that has the mpz_class, mpq_class, and mpf_class.

When I use the cumbersome mpz_t format, my numbers will increase to an arbitrary precision, but when I use the class wrapper, they act like _int32 and wrap around to negative when > 232.

Example Code:

Code: Select all

int i,j;
mpz_class a;
mpz_t b;

a=1;
mpz_init(b);
mpz_set_si(b,1L);
i=7037;
j=2123456789;

a=4*i*j;
mpz_mul_si(b,b,4L);
mpz_mul_si(b,b,i);
mpz_mul_si(b,b,j);
cout << a << endl;
cout << b << endl;
//Test if its just a problem with cout or an actual sign issue
mpz_set(b,a.get_mpz_t());
cout << b << endl;
Outputs the following:
-1998161660
59771061696722
-1998161660

So clearly the base C struct is working as I wish, but i'm not sure how to get the class wrapper to behave the same way. Anyone familiar with MPIR have any ideas?

Apologies for having to post here. I searched everywhere for some MPIR specific forum and could only find documentation hosting sites.
jaap
Posts: 559
Joined: Tue Mar 25, 2008 3:57 pm
Contact:

### Re: MPIR Question C++

I don't know the library, but your code does just what I would expect.

Code: Select all

int i,j;
mpz_class a;
mpz_t b;
i=7037;
j=2123456789;
a=4*i*j;
cout << a << endl;
The rhs of your assignment has three ints (4, i, and j), and therefore their multiplication will be done with int arithmetic only. The result, the overflowed value -1998161660, is what is assigned to a.

And then this obviously just reports that same value.

Code: Select all

//Test if its just a problem with cout or an actual sign issue
mpz_set(b,a.get_mpz_t());
cout << b << endl;
Try doing a = a*4*i*j. These multiplications are done left to right, and so all of them will involve at least one mpz_class object.
brainiac1530
Posts: 16
Joined: Sun Mar 02, 2014 2:32 pm

### Re: MPIR Question C++

Or use the compound assignment operator *= . I remember it being defined for the mpz_class, it will take default types or other mpz-types as arguments, and returns a reference to the original object, as expected for the operator.