문제

I'm implementing the sieve of eratosthenes algorithm in C++, and I've run into a problem. When I initialize my array to a very large value, like 1 million, it breaks because I'm allocating too large of an array to the stack. The answer in C would be to use malloc like this Sieve of Eratosthenes , but this solution does not work in C++ (to the best of my knowledge). Any ideas on how I could get this program to work with very large numbers by allocating the array in the heap instead of the stack? Thanks.

To see the problem I'm having, change the code below int integerList[1000], change 1000 to 1000000 or higher.

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;
}
도움이 되었습니까?

해결책

Allocating an array of size that large on the stack leads to stack overflow. To allocate it on the heap, you can do:

int *integerList = new int[1000000];

Or better, use a std::vector instead.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top