0

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?

KaliMa
  • 1,970
  • 6
  • 26
  • 51

1 Answers1

2

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
}
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • Also do I use mpz_t or mpz_class? – KaliMa Nov 27 '12 at 04:15
  • @KaLiMa mpz_class is natural for a C++ program. mpz_t can always be accessed with [get_mpz_t()](http://gmplib.org/manual/C_002b_002b-Interface-General.html#C_002b_002b-Interface-General) – Cubbi Nov 27 '12 at 04:21
  • For some reason that string line isn't working for me -- any reason? "to_string is not a member of std" – KaliMa Nov 27 '12 at 04:24
  • @KaLiMa your compiler might be too old to support it -- just start with `"1000000000000"`, the string. – Cubbi Nov 27 '12 at 04:31
  • Any reason why L=ceil((sqrt(v-4*N)-1)/4)-1; would throw "eval" errors? – KaliMa Nov 27 '12 at 04:55