views:

171

answers:

4

I would like to add 2 arbitrarily sized integers in C++. How can I go about doing this?

+2  A: 

Using the + operator?

kotlinski
+8  A: 

You can have a look at GMP, an arbitrary precision arithmetic library for C and C++.

isbadawi
+2  A: 

Something like libgmp will do arbitrary precision arithmetic.

WhirlWind
i want a code in c++.
BUKA
BUKA So, perhaps you could try the C++ class interface. http://gmplib.org/manual/C_002b_002b-Class-Interface.html#C_002b_002b-Class-Interface
WhirlWind
+2  A: 

Here's an example showing how to use the OpenSSL bignum implementation for arbitrary-precision arithmetic. My example does 264 + 265. I'm using Linux.

#include <cstdio>
#include <openssl/crypto.h>
#include <openssl/bn.h>

int main(int argc, char *argv[])
{
        static const char num1[] = "18446744073709551616";
        static const char num2[] = "36893488147419103232";

        BIGNUM *bn1 = NULL;
        BIGNUM *bn2 = NULL;

        BN_CTX *ctx = BN_CTX_new();

        BN_dec2bn(&bn1, num1); // convert the string to BIGNUM
        BN_dec2bn(&bn2, num2);

        BN_add(bn1, bn1, bn2); // bn1 = bn1 + bn2

        char *result_str = BN_bn2dec(bn1);  // convert the BIGNUM back to string
        printf("%s + %s = %s\n", num1, num2, result_str);
        OPENSSL_free(result_str);

        BN_free(bn1);
        BN_free(bn2);
        BN_CTX_free(ctx);

        return 0;
}

It produces this output:

18446744073709551616 + 36893488147419103232 = 55340232221128654848

You need to have OpenSSL installed with the development libraries. If you have Linux, install the development library from your package manager and link with libcrypto.so.

g++ bignum.cpp -o bignum -lcrypto

Or download the OpenSSL source and build the static library libcrypto.a and link with it statically.

g++ bignum.cpp -o bignum -I./openssl-1.0.0/include ./openssl-1.0.0/libcrypto.a

On Windows, you'll need to install from the Windows port of OpenSSL.

indiv