-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;
}
遞歸太深。用循環重寫。 – molbdnilo
遞歸函數應該返回遞歸調用的結果。 – molbdnilo
您是否執行過任何調試? –