2013-10-31 37 views
1

我需要對一年的練習進行暴力破解。編譯器不斷拋出此錯誤:C++:整數常量對於其類型來說太大

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

我的代碼是:

#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; 
} 

請注意,我已經與unsigned long long result(318338237039211050000ULL);

我使用gcc版本4.8.1

編輯試圖:

這是使用InfInt庫012的更正版本

#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; 
} 
+0

您應該使用ASCII表示法。 –

+0

使用'unsigned long long result = 318338237039211050000ULL;'失敗嗎?它可能只是它不喜歡這種初始化方法? –

+0

@ScottMermelstein:文字後綴不適用於* that *目的。如果存在這樣的類型,則整型文字已具有可表示它的類型。 –

回答

3

一個快速的方法來找出你的系統上的數字限制是使用std::numeric_limits。當我運行下面的代碼在我的系統上的輸出:

#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 ; 
} 

是:

ull 0 18446744073709551615 

我們可以看到最大值肯定比你的字面值較小:

18446744073709551615 
318338237039211050000 

所以你的整型文字太大,對於unsigned long long類型。

+0

謝謝。與其試圖找到支持這個操作的庫,我會用python實現相同的代碼。 – 01BTC10

+1

最後是通過這個庫http://code.google.com/p/infint/ – 01BTC10

1

你的問題很簡單,318338237039211050000ULL超出範圍。

假設一個64位的,64位值是良好的日誌10(2 -1)位十進制數(即,所有19位的值和一些較低20個值),318338237039211050000ull有21位數字。 2 -1(18446744073709551615ull)是最大值。

值318338237039211050000至少需要log10(318338237039211050000)/ log10(2)位。這是69位。

+2

做到的你不需要後綴;編譯器給它一個將保存該值的類型。 –

+0

@petebecker所有整數文字默認爲int,所以您需要使用後綴 – texasbruce

+0

@texasbruce:這是不正確的。未固定的十進制整數字面量的類型是可以表示其值的「int」,「long int」,「long long int」中的第一個。 (該列表在標準的早期版本中有所不同。)請參閱C++標準中的第2.14.2節[lex.icon]。 –

相關問題