Which data type to use for a very large numbers in C++?

随声附和 提交于 2019-12-03 06:17:41

long long is fine, but you have to use a suffix on the literal.

long long x = 600851475143ll; // can use LL instead if you prefer.

If you leave the ll off the end of the literal, then the compiler assumes that you want it to be an int, which in most cases is a 32-bit signed number. 32-bits aren't enough to store that large value, hence the warning. By adding the ll, you signify to the compiler that the literal should be interpreted as a long long, which is big enough to store the value.

The suffix is also useful for specifying which overload to call for a function. For example:

void foo(long long x) {}
void foo(int x) {}

int main()
{
    foo(0); // calls foo(int x)
    foo(0LL); // calls foo(long long x)
}

You had the right idea with long long int (or unsigned long long int), but to prevent the warning, you need to tell the compiler that the constant is a long long int:

long long int value = 600851475143LL;

Those "L"s can be lower-case, but I'd advise against it -- depending on the font, a lower-case "L" often looks a lot like a one digit ("1") instead.

Have a look at the GNU MP Bignum library http://gmplib.org/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!