Big number in C++

后端 未结 9 1515
暖寄归人
暖寄归人 2020-12-16 19:13

I am trying to place a big number in a C++ variable. The number is 600851475143

I tried unsigned long long int but got an error saying it the constant was too big.

相关标签:
9条回答
  • 2020-12-16 19:56

    The number is 600851475143 isn't too large for a long long int but you need to use the LL suffix when using a long long constants (ULL for unsigned long long int):

    unsigned long long int num = 600851475143ULL;
    
    0 讨论(0)
  • 2020-12-16 19:59

    You can specify an integer literal as long by the suffix L.
    You can specify an integer literal as long long by the suffix LL.

    #include <iostream>
    
    int main()
    {
        long long num = 600851475143LL;
    
        std::cout << num;
    }
    
    0 讨论(0)
  • 2020-12-16 19:59

    Is there a bigint lib to link in or a bigint.cpp to compile?

    0 讨论(0)
  • 2020-12-16 20:00

    If you are getting undefined reference errors for the bignum library, you probably didn't link it. On Unix, you will have to pass an option like -lbigint. If you are using an IDE, you will have to find the linker settings and add the library.

    As for the numbers, as has already been said, a natural constant defaults to int type. You must use LL/ll to get a long long.

    0 讨论(0)
  • 2020-12-16 20:04

    In a more general case when you cannot fit your number in a long long, and can live with the GNU LGPL license (http://www.gnu.org/copyleft/lesser.html), I would suggest trying the GNU Multiprecision Library (http://gmplib.org/).

    It is extremely fast, written in C and comes with a very cool C++-wrapper-library.

    0 讨论(0)
  • 2020-12-16 20:06

    The first thing to do in this case is to figure out what is the largest number that you can fit into an unsigned long long. Since it is 64 bit, the largest number would be 2^64-1 = 18446744073709551615, which is larger than your number. Then you know that you are doing something wrong, and you look at the answer by Martin York to see how to fix it.

    0 讨论(0)
提交回复
热议问题