ecjb
ecjb

Reputation: 5449

Use of bigint in C (Example using libtomath library)

I want to use large integer to do some computation similar to the following:

#include<stdio.h>

int main (){
  long a = 123456789123456789123456789123456789;
  long b = 2*b;

  printf("%ld", a);
  printf("\n");
  printf("%ld",b );
  return 0;
}

which currently generates:

main.c:4:12: error: integer literal is too large to be represented in any integer
      type
  long a = 123456789123456789123456789123456789;
           ^
1 error generated.

I know there is a library called libtomath as pointed by this other SO question but I could not find any example and and I'm new to C and don't know how to read through a library to find the answer. How could I modify the code using libtomath (or other solutions)?

Upvotes: 0

Views: 549

Answers (2)

alinsoar
alinsoar

Reputation: 15793

The best way is to use 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;
}

You can use it like this:

% gcc addbig.c -lgmp
% ./a.out 49378437483789437894739874389\ 
          74387438978437894378743874837
123765876462227332273483749226
148774877956875788757487749674
% ./a.out 1111111111111111111111111111111111111111111\
          2222222222222222222222222222222222222222222
3333333333333333333333333333333333333333333
4444444444444444444444444444444444444444444

Upvotes: 2

shiv
shiv

Reputation: 1952

You can process bn.tex file given @ https://github.com/libtom/libtommath/tree/develop/doc to generate PDF docs of libtomath. If you cannot do that let me know and I will generate PDF for you.

Upvotes: 1

Related Questions