我正在實施C++中的eratosthenes算法篩選,並且遇到了問題。當我將我的數組初始化爲一個非常大的值(例如100萬)時,它會因爲我將大數組分配給堆棧而中斷。 C中的答案是使用像這樣的malloc,像這個Sieve of Eratosthenes,但是這個解決方案在C++中是不行的(據我所知)。關於如何通過在堆而不是堆棧中分配數組來獲得此程序的大量數據的任何想法?謝謝。堆陣列分配而不是堆棧
要查看我遇到的問題,請更改下面的代碼int integerList [1000],將1000更改爲1000000或更高。
int main(void)
{
int userInput = 0;
int integerList[1000] = {};
cout << "Please pick a number to find all prime numbers "
<< "from 2 to that number: " << endl;
//for the sake of writing out algorithm only, assume correct input
cin >> userInput;
//initialize array
for (int i = 2; i <= userInput; i++)
{
integerList[i] = i;
}
//implementation of the algorithm
for (int i = 2; i < userInput; i++)
{
if (integerList[i] != 0)
{
for (int j = 2; j < userInput; j++)
{
integerList[j*integerList[i]] = 0;
if (integerList[i] * j > userInput)
{
break;
}
}
}
}
for (int i = 0; i < userInput; i++)
{
if (integerList[i] != 0)
{
cout << integerList[i] << " ";
}
}
system("Pause");
return 0;
}
相關:你從字面上需要一個* bits *的數組,用於篩選一個erath。該數組不需要包含首先用於訪問它的索引的值。如果標誌數組'sieve [i]'被設置(非零),則已知素數'i'是如此(主要)。簡短版本:您可以使用「N/CHAR_BIT」*字節*在篩選器中找到所有素數爲「N」或以下的「N」; (如果在開始之前排除偶數的所有偶數,則*的一半*)。 – WhozCraig
算法和素數標籤與此問題完全無關。標題中的Eratosthenes篩網也是無關緊要的。這是我在看完整個問題後發現的。我曾建議編輯,刪除不相關的標籤,並使標題更具相關性,這被接受,但後來又回滾了(跆拳道?你甚至讀過Rollback先生?)我再次嘗試建議編輯,該編輯回滾到修訂版2被我的回滾拒絕。有人可以真正閱讀這個問題嗎?如果他們同意,可以回滾到第2版?謝謝。 – RelevantTitlesAreBestTitles