在 C 中使用 bigint(使用 libtomath 库的示例)
Use of bigint in C (Example using libtomath library)
我想使用大整数来做一些类似下面的计算:
#include<stdio.h>
int main (){
long a = 123456789123456789123456789123456789;
long b = 2*b;
printf("%ld", a);
printf("\n");
printf("%ld",b );
return 0;
}
当前生成:
main.c:4:12: error: integer literal is too large to be represented in any integer
type
long a = 123456789123456789123456789123456789;
^
1 error generated.
我知道有一个名为 libtomath as pointed by this other SO question 的库,但我找不到任何示例,而且我是 C 的新手,不知道如何通读库来找到答案。我如何使用 libtomath(或其他解决方案)修改代码?
您可以处理给定@ https://github.com/libtom/libtommath/tree/develop/doc 的 bn.tex
个文件以生成 libtomath
的 PDF 文档。如果您做不到,请告诉我,我会为您生成 PDF。
最好的方法是使用gmp
。
#include <gmp.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
mpz_t x,y,two;
if (argc<3)
return 1;
mpz_init_set_str (x, argv[1], 10);
mpz_init_set_str (y, argv[2], 10);
mpz_init_set_ui(two, 2U);
mpz_add (x,x,y);/*x<-x+y*/
mpz_mul (y,y,two);/*y<-y+y*/
printf("%s\n", mpz_get_str (NULL, 10, x));
printf("%s\n", mpz_get_str (NULL, 10, y));
return 0;
}
你可以这样使用它:
% gcc addbig.c -lgmp
% ./a.out 49378437483789437894739874389\
74387438978437894378743874837
123765876462227332273483749226
148774877956875788757487749674
% ./a.out 1111111111111111111111111111111111111111111\
2222222222222222222222222222222222222222222
3333333333333333333333333333333333333333333
4444444444444444444444444444444444444444444
我想使用大整数来做一些类似下面的计算:
#include<stdio.h>
int main (){
long a = 123456789123456789123456789123456789;
long b = 2*b;
printf("%ld", a);
printf("\n");
printf("%ld",b );
return 0;
}
当前生成:
main.c:4:12: error: integer literal is too large to be represented in any integer
type
long a = 123456789123456789123456789123456789;
^
1 error generated.
我知道有一个名为 libtomath as pointed by this other SO question 的库,但我找不到任何示例,而且我是 C 的新手,不知道如何通读库来找到答案。我如何使用 libtomath(或其他解决方案)修改代码?
您可以处理给定@ https://github.com/libtom/libtommath/tree/develop/doc 的 bn.tex
个文件以生成 libtomath
的 PDF 文档。如果您做不到,请告诉我,我会为您生成 PDF。
最好的方法是使用gmp
。
#include <gmp.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
mpz_t x,y,two;
if (argc<3)
return 1;
mpz_init_set_str (x, argv[1], 10);
mpz_init_set_str (y, argv[2], 10);
mpz_init_set_ui(two, 2U);
mpz_add (x,x,y);/*x<-x+y*/
mpz_mul (y,y,two);/*y<-y+y*/
printf("%s\n", mpz_get_str (NULL, 10, x));
printf("%s\n", mpz_get_str (NULL, 10, y));
return 0;
}
你可以这样使用它:
% gcc addbig.c -lgmp
% ./a.out 49378437483789437894739874389\
74387438978437894378743874837
123765876462227332273483749226
148774877956875788757487749674
% ./a.out 1111111111111111111111111111111111111111111\
2222222222222222222222222222222222222222222
3333333333333333333333333333333333333333333
4444444444444444444444444444444444444444444