18

Possible Duplicate:
long long in C/C++

Writing a simple program for a project Euler problem. Refuses to compile because "integer constant is too large for "long" type", even though it should be well within the size limits of an unsigned long long. Using the dev-c++ compiler.

code in question:

#include <iostream>

bool isprime (unsigned long long i)
{
    if(i==1||i==0) return false;
    if(i==2) return true;
    for(unsigned long long k=2;k!=i-1;k++)
    {      
        if(i%k==0) return false;
    }
    return true;
}

int main()
{
    for(unsigned long long i=600851475143;i>=0;i--) //problematic line
    {
        if(isprime(i))
        {
            std::cout<<i;
            std::cin.get();
            return 0;
        }
    }
}
Community
  • 1
  • 1
Bacu
  • 539
  • 2
  • 4
  • 12

3 Answers3

31

Try an "ULL" suffix: 600851475143ULL

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
4

Your literal as typed has type int which isn't big enough to hold the value. Try 600851475143ULL as a first fix.

Note even with that, your for loop will never terminate since an unsigned can never be less than 0. Instead, use a long long and 600851475143LL.

Mark B
  • 95,107
  • 10
  • 109
  • 188
0

Must be a limitation of dev-c++ support for long long datatype. It compiles fine on MS VC++ 2010.

FumbleFingers
  • 226
  • 5
  • 15
  • 3
    That would be a bug in MS VC++ 2010 then, unless its native `int` type is 64 bits. The literal as typed is an `int`. – Mark B Apr 04 '11 at 16:51
  • I don't want to get into a long discussion on this, but I'd always understood that a good compiler should choose the most appropriate datatype for internal representation of literals that don't explicitly specify it. In this case the value is capable of being stored in a **long long**, but it seems the copmpiler chooses to use just **long** before even looking at either the actual value, or the assignment destination. I'm no great fan of MS in general, but their way does seem 'better' to me in this case. – FumbleFingers Apr 04 '11 at 17:38
  • ps - I know the formal definition for c++ says numeric literals are stored in whatever the compiler uses as its native **int** type. But I wouldn't call the MS approach a *bug* - it's more of a *non-standard extension* to me. – FumbleFingers Apr 04 '11 at 17:47