Search code examples
c++gmp

How do I use GMP properly to do this operation?


My code in C++

   long long N=1000000000000LL;
   long long a = N;
   mpz_class v;
   mpz_mul(v, a, a); 
   cout<<v<<endl; //I want this to show 1000000000002000000000001
   long long U=((sqrt(4*N+v)-1)/4);  //not sure how to do this in GMP at all
   cout << U << endl; //should show 250000000000

This is a snippet that shows what kind of operations I want to do. But I am not experienced enough with GMP to get it down, and the documentation is unclear to me. How do I correct all this?


Solution

  • mpz_class has no constructor from long long (it only goes up to unsigned long), so you'd have to use an intermediate string:

    #include <gmpxx.h>
    #include <iostream>
    #include <string>
    
    int main()
    {
        long long N = 1000000000000LL;
        mpz_class a(std::to_string(N).c_str());
        mpz_class v = a*a;
        std::cout << v << '\n'; // shows 1000000000000000000000000
        std::cout << (a+1) * (a+1) << '\n'; // THIS shows 1000000000002000000000001
    
        mpz_class U = ((sqrt(4*a+v)-1)/4);
        std::cout << U << '\n'; // shows 250000000000
    }