2017-04-23 20 views
-1

我對C++很新,所以我不知道很多,只是非常基礎。我試圖編寫一個程序來查找數字的最大素數因子。它適用於5位數字,但當我輸入一個大於5位的數字時,程序崩潰。我其實需要使用12位數字的程序。任何人都可以請建議我應該在代碼中更改什麼。該代碼是通過在每個函數內的幾個地方增加一個簡單的cout語句來確定您的錯誤發生如下當我使用大數字時,C++程序崩潰

#include <iostream> 

using namespace std; 

bool checkPrime(uint64_t a, uint64_t x) 
{ 
    a = a + 1; 
    uint64_t b = a*a; 
    if (b <= x) 
    { 
     if (x%a == 0) 
     { 
      return false; 
     } 
     else { 
      checkPrime(a, x); 
     } 
    } 
    else { 
     return true; 
    } 
} 

uint64_t findPrime(uint64_t a, uint64_t x, uint64_t h) 
{ 
    a = a+1; 
    if (a <= x) 
    { 
     if (x%a == 0) 
     { 
      if (checkPrime(1, a)) 
      { 
       h = a; 
       findPrime(a, x, h); 
      } 
      else 
      { 
       h = h; 
       findPrime(a, x, h); 
      } 

     } 
     else 
     { 
      h = h; 
      findPrime(a, x, h); 
     } 
    } 
    else { 
     return h; 
    } 
} 

int main() 
{ 
    cout << "Hello world!" << endl; 
    uint64_t f; 
    cout << "Enter the Number: "; 
    cin >> f; 
    uint64_t z = findPrime(1, f, 1); 
    cout << "Largest Prime Factor is " << z << endl; 


    return 0; 
} 
+0

遞歸太深。用循環重寫。 – molbdnilo

+2

遞歸函數應該返回遞歸調用的結果。 – molbdnilo

+0

您是否執行過任何調試? –

回答

0

我將開始。

它可能,正如molbdnile所示,你的遞歸太深。使用a作爲您的計數器,可能會更好地將其重寫爲forloop。

另一個潛在問題是

uint64_t b = a*a; 

如果一個足夠大它乘以本身可能溢出b

+0

非常感謝,我在循環中接受教程,因爲我還沒有到現在。我會用cout的建議,它幫了很多。 –