How to perform operations with really large numbers in C/C++?

Asked

Viewed 763 times

4

How to perform sum operations with really large numbers? Numbers that can reach 50 or 1000 digits.

Is it necessary to install a library? How to install this library in Ubuntu?

You can post some example of the code by adding the two values below?

35398664372827112653829987240784473053190104293586 + 17423706905851860660448207621209813287860733969412

1 answer

8


You need to add a lib to work with very large numbers, on Ubuntu I suggest the GMP. Install GMP with apt-get install libgmp-dev.

An example of summation using libgmp:

#include <stdio.h>
#include <gmp.h>
// Compile com: 
// gcc -lgmp -lm -o add_ex add_ex.c
int main()
{
    mpz_t a, b, soma;
    mpz_init_set_str(a, "35398664372827112653829987240784473053190104293586", 10);
    mpz_init_set_str(b, "17423706905851860660448207621209813287860733969412", 10);
    mpz_add (soma, a, b); 
    mpz_out_str(stdout, 10, a); 
    printf("\n + \n");
    mpz_out_str(stdout, 10,b); 
    printf("\n = \n");
    mpz_out_str(stdout, 10, soma);
    printf("\n");
    return 0;
}

The output:

35398664372827112653829987240784473053190104293586
 +
17423706905851860660448207621209813287860733969412
 =
52822371278678973314278194861994286341050838262998

Browser other questions tagged

You are not signed in. Login or sign up in order to post.