C++ : integer constant is too large for its type

2020-03-30 07:34发布

问题:

I need to bruteforce a year for an exercise. The compiler keep throwing this error:

bruteforceJS12.cpp:8:28: warning: integer constant is too large for its type [enabled by default]

My code is:

#include <iostream>

using namespace std;

int main(){

    unsigned long long year(0);
    unsigned long long result(318338237039211050000);
    unsigned long long pass(1337);

    while (pass != result)
    {
    for (unsigned long long i = 1; i<= year; i++)
        {

        pass += year * i * year;

        }

        cout << "pass not cracked with year = " << year << endl;
        ++year;

    }

        cout << "pass cracked with year = " << year << endl;
}

Note that I already tried with unsigned long long result(318338237039211050000ULL);

I'm using gcc version 4.8.1

EDIT:

Here is the corrected version using InfInt library http://code.google.com/p/infint/

#include <iostream>
#include "InfInt.h"

using namespace std;

int main(){

    InfInt year = "113";
    InfInt result = "318338237039211050000";
    InfInt pass= "1337";

    while (pass != result)
    {
    for (InfInt i = 1; i<= year; i++)
        {

        pass += year * i * year;

        }

        cout << "year = " << year << "  pass = " << pass <<  endl;
        ++year;

    }

        cout << "pass cracked with year = " << year << endl;
}

回答1:

A quick way to figure out the numeric limits on your system would be to use std::numeric_limits. The output on my system when I run the following code:

#include <iostream>
#include <limits>

int main()
{   
     std::cout << "ull\t"
              << std::numeric_limits<unsigned long long>::lowest() << '\t'
              << std::numeric_limits<unsigned long long>::max() << std::endl ;
}

is:

ull 0   18446744073709551615

we can see the max value is definitely smaller than your literal value:

 18446744073709551615
 318338237039211050000

So your integer literal is just too large for unsigned long long type.



回答2:

Your problem is simply that 318338237039211050000ULL is out of range.

Assuming a 64 bit type, a 64 bit value is good for log10( 264-1) decimal digits (i.e. all 19 digit values and some lower 20 digit values), 318338237039211050000ull has 21 digits. 264-1 (18446744073709551615ull) is the maximum.

The value 318338237039211050000 requires at least log10(318338237039211050000)/log10(2) bits. That's 69 bits.



标签: c++ gcc