So, I am a beginner and as exercise I wrote a code to show all prime number up to the input. It worked pretty well, but then I wanted to see up to which number could my computer process in a resonable amount of time. I got into two problems. First, at least on my pc, the maximum array size that I can create without crashing is exactly 519.371(i.e.:array[519371]). And second, making some ajustments I actually could allow an input for which my pc couldn't calculate in a relative small time, even though around 40% ,peaking 50% sometimes, of the processor was doing this task. To calculate the primes in between 2 and 5.000.000 - without any other things being done - my pc took
4 minutes and 38 seconds.
Said so, this are my questions:
1.Is there any way to expand the maximum size of arrays? Maybe allocating more memory for it? I need it because the array I'm using is actually to store the primes in order to calculate the next, and am too lazy to try to use two arrays.
2.Is there any way to expand the processors usage to make the code faster?
No overclocking solution.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main () {
int n, l=3, x=2, j, d;
cout << "Choose up to which number would you like to know the prime numbers.";
cout << "\nThe maximum input is 5.000.000, and the minimum is 5: ";
cin >> n;
cout << endl << endl;
while (n>5000000||n<5) {
cout << "Invalid input, try again: ";
cin >> n;
cout << endl << endl;
}
int Primos[int (ceil(n/(log (n)-1.1)))];
Primos[2]=2;
cout << "2\t";
do {
j=2;
do {
d=l%Primos[j];
++j;
} while (x-j>=0&&d!=0&&Primos[j]<=l/2);
if (d!=0) {
cout << l << "\t";
++x;
Primos[x]=l;
}
l = l + 2;
} while (n>l-1);
cout << endl << endl << "Finished" << "\n\n";
cout << "Number of primes: " << (x-1) << "\n\n";
system("Pause");
return 0;
}
|