views:

199

answers:

5

I have to store the number 600851475143 in my program. I tried to store it in long long int variable and long double as well but on compiling it shows the error "integer constant is too large for "long" type.". I have also tried unsigned long long int too. I m using MinGW 5.1.6 for running g++ on windows. What datatype should I use o store the number..?

+20  A: 

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)
}
Peter Alexander
well thanks but can anyone explain me why do we do this? what happens by adding the literals??
vaibhav
@vaibhav: See my edit.
Peter Alexander
You really should use upper-case LL here.
configurator
I did add that as a comment, but honestly I don't think I've ever confused an l with a 1 in Courier New, which is what most editors use as their font.
Peter Alexander
A: 

look here: http://stackoverflow.com/questions/117429/inputting-large-numbers-in-c it's similar to your question

nilphilus
A: 

Here is a similar old question with answers.

rics
+6  A: 

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.

Jerry Coffin
+2  A: 

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

Pierre
Way to shoot a mouse with an Elephant gun.
Billy ONeal