Assignment: Write a C ++ program on Ertostenes sieve and print all major numbers between 1 and 1,000,000. I have realized that when I actually have a large number like 1,000,000, the program stops working and this program works perfectly well for small numbers like 9,000. Is there a way to form 1,000,000 integer array sizes?
#include & lt; Iostream & gt; using namespace std; Zero sieve (int [], int num); Int main () {int numOfElements; Cout & lt; & Lt; "Please input number" & lt; & Lt; Endl; CIN & gt; & Gt; NumOfElements; Int [numOfElements]; Sieve (primers, numbers); Return 0; } // prime number: any whole number greater than one and has only numbers and the same factors are zero sieve (integer prime [], integer number) {int i, j; For (int a = 0; a & lt; num; a ++) {principal [a] = a + 1; } Prime Minister [0] = 0; // We know 1 is not the prime minister; For (i = 2; i & lt; = num; i ++) {if (principal [i-1]! = 0) {cout < & Lt; I & lt; & Lt; Endl; } For (j = i * i; j & lt; = num; j + = i) {principal [j-1] = 0; } <}
being able to write int primeArray [numOfElements];
(This is a variable length Array) is an compiler extension : not part of standard C ++ I hope your compiler is warning you about it; If not, then make sure the warning level is set correctly.
But in this case it is an important issue: an effort to allocate such a large array will fail on the stack will fail. Stacks are limited to the size of a sequence of megabytes of magnitude.
The best solution is to use a std :: vector
, which is (i) standard C ++, and (ii) stack Will allocate memory.
If you want to use an array, then you int * primeArray = newAnt [numOfElements]
. Do not forget to clear memory by using Delete []
.
No comments:
Post a Comment