How to add 2 arbitrarily sized integers in C++?

前端 未结 3 605
离开以前
离开以前 2020-11-27 07:38

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

3条回答
  •  死守一世寂寞
    2020-11-27 07:54

    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 
    #include 
    #include 
    
    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.

提交回复
热议问题