GMP library全称是GNU Multiple Precision Arithmetic Library,即GNU高精度算术运算库。先到官网下载相应的包。
安装库
我下的是gmp-6.2.0.tar.xz。cd到下载目录,分两步解压:
$ xz -d gmp-6.2.0.tar.xz
$ tar -xvf gmp-6.2.0.tar
解压完后cd到文件夹gmp-6.2.0对其进行编译:
$ cd gmp-6.2.0
$ ./configure --enable-cxx
$ make -j4 # 4 核心编译速度更快 也可以直接 make
出现了一个问题:
checking for suitable m4... configure: error: No usable m4 in $PATH or /usr/5bin (see config.log for reasons).
是因为没有m4,安装即可:
sudo apt-get install m4
对编译进行自测:
$ make check
对库进行安装(默认路径为/usr/local)
$ sudo make install
使用库
链接到 libgmp 库,使用选项 -lgmp:
gcc myprogram.c -lgmp
c++函数在 libgmpxx 库中,因此需要额外的编译选项:
g++ mycxxprog.cc -lgmpxx -lgmp
实例
#include <iostream>
#include <gmpxx.h>
using namespace std;
int main()
{
mpz_t a,b,c; // define
mpz_init(a); // initialize
mpz_init(b);
mpz_init(c);
gmp_scanf("%Zd%Zd",a,b); // input
mpz_add(c,a,b); // compute c = a + b
gmp_printf("%Zd\n",c); // output
mpz_clear(a); // clear memory
mpz_clear(b);
mpz_clear(c);
return 0;
}
$ g++ -o testgmp.out testgmp.cpp -lgmpxx -lgmp
$ ./testgmp.out
324327543564685049860389045809768327483265873264578346593489
100000000000000000000000000000000000000000000000000000000001
结果:
424327543564685049860389045809768327483265873264578346593490