c++gmp

GMP library for C++: converting `mpz_class` to `unsigned long`


My first experience with GMP big integers... The simple test below can't be compiled because the get_ui member function is not found. The function get_ui is mentioned in the GMP manual.

#include <iostream>
#include <gmpxx.h>

using std::cout;
using std::endl;

int main()
{
  mpz_class a(1);
  for (auto n = 0U; n < 100; ++n) a *= 10;
  cout << a << endl;
  auto b = a % 10;
  cout << b << endl;
  auto c = b.get_ui();
  cout << c << endl;
}

The compiler output:

tc0001.cpp:27:14: error: ‘class __gmp_expr<__mpz_struct [1], __gmp_binary_expr<__gmp_expr<__mpz_struct [1], __mpz_struct [1]>, long int, __gmp_binary_modulus> >’ has no member named ‘get_ui’
   27 |   auto c = b.get_ui();
      |              ^~~~~~

The system environment:

What's the problem here?


Solution

  • The problem is that because you used auto to declare b, the type is not mpz_class, but rather an internal type used for optimizing calculations. To call any mpz_class methods, you'll need to convert it to an mpz_class.

    The easiest fix is to declare b as mpz_class instead of auto:

    mpz_class b = a % 10;
    

    alternately you can explicitly convert to mpz_class:

    auto c = mpz_class(b).get_ui();