2014-05-24 73 views
1

我正在解決一個問題,雖然我已經解決了(過了很久),但我想知道我的實現有什麼問題。 我在Windows中用C++和Python編寫了我的解決方案。我正在嘗試與我的Python的codeskulptor合作,它給了我一些TIMELIMITERROR。我切換到C++語言,它給了我一些奇怪的錯誤。我啓動了我的虛擬機,以便試圖找出爲什麼我的C++代碼失敗(我使用了Borland的BCC32)。我可以檢測到由Collat​​z序列生成的長整型數,這可能會導致我的程序崩潰。在Linux下,我得到了幾乎相同的錯誤,雖然我可以在Linux下看到該程序運行並可以操縱很長的數字(使用g ++編譯器)。 在Linux下工作時,我可以使用我爲Windows開發的相同的Python程序,它的工作很簡單。我想知道爲什麼C++在Windows和Linux上都失敗了。Collat​​z C++代碼問題

in Python: 

def Collatz(num): 
    temp = [] 
    temp.append(num) 
    while num> 1: 
     num = num%2==0 and num/2 or num*3+1 
     temp.append(num) 
    return temp 

in C++: 

vector<unsigned long> collatz(int num) 
{ 
    vector<unsigned long> intList; 
    intList.push_back(num); 
    while(num>1) 
    { 
     if (num%2==0) num /=2; 
    else num=num*3+1; 
    intList.push_back(num); 
    } 
    return intList; 
} 

這兩個片碼的僅僅是功能:

奇怪的是,這兩個碼效果很好計算所述序列爲13或999999但是例如C++未能計算序列爲837799。 ..也許它與矢量容器大小有關?

回答

1

因爲你numint,而你在在Collat​​z系列837799元素991661525後獲得的溢出(所有操作都與int完成的,所以你溢出num=num*3+1乘以991661525*3+1時)。在函數定義

vector<unsigned long> collatz(unsigned long num) 

更改numunsigned long,也將努力!

+0

是啊!多麼愚蠢的檢查...我更改了矢量聲明,並沒有檢查num變量......謝謝你 – froycard