歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 開源算法庫GMP的安裝與調試

開源算法庫GMP的安裝與調試

日期:2017/3/1 10:11:31   编辑:Linux編程

GMP簡介:
GMP是一個任意精度的開源算術庫,可用於符號整數,有理數,浮點數計算。算數庫對於有沒有實際的限制,唯一的限制是計算機的內存。 GMP具有豐富的函數集並且函數都有通用的接口。

GMP的安裝:

環境:Ubuntu 11.10

Terminal中運行:
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\n",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\n",i,j);
gmp_printf("%Zd\n%Zd\n",p,q);
mpz_addmul(s,p,q);//calculate result
//gmp_printf("the result is %Zd\n",s);
pt=mpz_get_str(pt,10,s);//get string from s
//printf("%s\n",pt);
mpz_clear(s);
return pt;
}

通過兩個字符串變量將乘數傳進去,再傳回結果指針。

算得結果:
the result is 289589963907942.
下一步是在sipesc力學平台上做成插件。

Copyright © Linux教程網 All Rights Reserved