高精度运算库gmp

2023-07-27

网址:www.gmplib.org

我下载的是 6.1.2版本:https://gmplib.org/download/gmp/gmp-6.1.2.tar.bz2

执行操作如下:

1.  tar -jvxf gmp-6.1.2.tar.bz2
2.  ./configure --enable-cxx
注意:在configure的时候一定要加上--enable-cxx,否则不能使用C++库gmpxx.h
3.  make
4.  make check
5.  sudo make intall

用c语言编一个例子:

#include<gmpxx.h>
using namespace std;
int main()
{
mpz_t a, b, c, d;
mpz_init(a);
mpz_init(b);
mpz_init(c);
mpz_init(d);
//计算2的1000次方
mpz_init_set_ui(a, );
mpz_pow_ui(c, a, );
gmp_printf("c = %Zd\n", c); //计算12345678900987654321*98765432100123456789
mpz_init_set_str(b, "", );//10进制
mpz_init_set_str(c, "", );
mpz_mul(d, b, c);
gmp_printf("d = %Zd\n", d);
mpz_clear(a);
mpz_clear(b);
mpz_clear(c);
mpz_clear(d);
return ;
}

用c++要简单很多:

#include<gmpxx.h>
using namespace std;
int main()
{
mpz_t a, b, c, d;
mpz_init(a);
mpz_init(b);
mpz_init(c);
mpz_init(d);
//计算2的1000次方
mpz_init_set_ui(a, );
mpz_pow_ui(c, a, );
gmp_printf("c = %Zd\n", c); //计算12345678900987654321*98765432100123456789
mpz_init_set_str(b, "", );//10进制
mpz_init_set_str(c, "", );
mpz_mul(d, b, c);
gmp_printf("d = %Zd\n", d);
mpz_clear(a);
mpz_clear(b);
mpz_clear(c);
mpz_clear(d);
return ;
}

注意,编译时要链接gmp库:

g++ name.cpp -o name.o -lgmpxx -lgmp

高精度运算库gmp的相关教程结束。