goodness, that is slow. This isnt the best code; its something I did ages ago for a similar homework posted here, but I just did x = 600M in seconds.
using the world's worst timer, the dos prompt itself (prompt $t$g command):
1 2 3
|
9:56:35.37>a
11113 is prime
9:56:44.60>
| |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
vector<bool>& initpn()
{
unsigned long long i,j, s = 600000000;
static vector<bool> pn(s,true);
for(i = 3; i < pn.size(); i+=2)
{
if(pn[i])
for(j = i*2; j < pn.size(); j+=i)
pn[j] = false;
}
return pn;
}
int main()
{
vector<bool> &p = initpn();
unsigned long long u = 11113;
//cout << "enter number\n";
//cin >> u;
if(p[u]) cout << u <<" is prime\n";
else cout << u << " is not prime\n";
}
| |
what why etc..
- vector bool is often optimized to use 1 bit per entry by the compiler.
- it does not test, it just sets. take 2: then loop every other number and set it to false. then take 3, loop every 3rd number and set that to false. then take 5 (the next true value), loop every 5th number and set them all false. then take 7 (the next true value so far)... etc.... this is the 'sieve of some guy whos name I cannot spell' or 'prime sieve' for short, a well known algorithm. Its one of the very cool extremely old algorithms, like the square root, that existed almost since the wheel and fire were new. you can manually set 1 and 0 if you like, gigo and all that.
- at some point even vector bool won't hold any more, of course.
edit, just realized a little tweak:
for(j = i*3; j < pn.size(); j+=i*2)//3-> 9, 15, 21 ... 5 -> 15, 25, 35, ... not much but skips the redundant evens. have to add a loop to do the even's one time, though. This pulls 600M to < 10 sec and 2^32 to < 3 min on my somewhat wimpy work laptop.