GMP简介: GMP是一个任意精度的开源算术库,可用于符号整数,有理数,浮点数计算。算数库对于有没有实际的限制,唯一的限制是计算机的内存。 GMP具有丰富的函数集并且函数都有通用的接口。GMP的安装:环境:Ubuntu 11.10Terminal中运行: sudo apt-get install libgmp3-dev gmp的调试: 新建.c文件,输入一下代码。 #include<gmp.h> #include<stdio.h> void main() { mpz_t s,n; int i; mpz_init(s);//init s,the value is 0 mpz_init(n); for(i=1;i<1111111111;i++) { mpz_add_ui(n,n,1);//set n to n+1 mpz_addmul(s,n,n);//add n*n to s } gmp_printf("the sum is %Zd
",s); mpz_clear(s); } Termial 中编译: gcc test.c -o test -lgmp Termial中运行: ./test 算了大概3分钟,得到结果: the sum is 457247370073159579654778235 函数封装: 封装的目的是给出通用的接口,下面实现的就是大数的乘法。 #include<gmp.h> #include<stdio.h> char* BigMul(char* m,char* n); void main() { char* p=NULL; char *a="12345678"; char *b="23456789"; p=BigMul(a,b); printf("the result is %s./n",p); } char* BigMul(char* m,char* n) { int i,j; char* pt=NULL; mpz_t s,p,q; mpz_init(s); i=mpz_init_set_str(p,m,10);//get number from m j=mpz_init_set_str(q,n,10); //printf("i,j:%d,%d
",i,j); gmp_printf("%Zd
%Zd
",p,q); mpz_addmul(s,p,q);//calculate result //gmp_printf("the result is %Zd
",s); pt=mpz_get_str(pt,10,s);//get string from s //printf("%s
",pt); mpz_clear(s); return pt; }通过两个字符串变量将乘数传进去,再传回结果指针。算得结果: the result is 289589963907942. 下一步是在sipesc力学平台上做成插件。