简体   繁体   中英

C++ GMP equivalent of pow (a,b) using mpz_class

I'm trying to calculate a to the power of b where a and b are of mpz_class type. There aren't enough samples and explanations on the GMP manual. Here is my take with the comments:

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

int main(){
    mpz_class r;
    mpz_class a = 2;
    mpz_class b = 3;

    mpz_ui_pow_ui (r.get_mpz_t(), 2, 3);// Works
    // mpz_ui_pow_ui (r.get_mpz_t(), a.get_mpz_t(), b.get_mpz_t());
    /* Doesn't work. Gives
 invalid conversion from 'mpz_ptr' {aka '__mpz_struct*'} to 'long unsigned int' [-fpermissive] error. In the the official documentation, there a bunch of similar pow functions such as
mpz_powm(mpz_t rop , const mpz_t base , const mpz_t exp , const mpz_t mod) without any samples.
    */
    std::cout << r << '\n';
}

How to do it?

I've tried:

mpz_pow_ui (r.get_mpz_t(), a.get_mpz_t(), b.get_mpz_t());

and it gave the same error.

Because b is 3 ie a very small number, I've tried:

mpz_pow_ui (r.get_mpz_t(), a.get_mpz_t(), b.mpz_get_ui());

and it gave no member named __gmpz_get_ui error.

There is no function in GMP to raise one unbounded integer to the power of another. presumably because any such calculation would overflow with numbers that are too big to fit into fixed size integers.

The closest to what you want is mpz_pow_ui , which raises a unbounded integer to the power of a fixed size integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM