My code calculates primes from one to n. I have verified that the code always produces all the primes in that range correctly.
Are there any optimizations that I can make? Are there any bad programming practices besides variable names (e.g. l is close to 1)? Any better normal Windows API? I am using the Sieve of Eratosthenes.
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <Windows.h>
using namespace std;
#define printprimes() //for each(bool b in primes) cout << b << endl;
int main(int argc, char* argv[])
{
const double s = GetTickCount();
unsigned long long numt;
if(argc < 2) {
cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
return 1;
}
else if(atoi(argv[1])<1) {
cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
return 1;
}
numt = atol(argv[1])+1;
bool skipprint = false;
if(argc >=3) if(!strcmp(argv[2], "noprint")) skipprint = true;
vector<bool> primes(numt);
primes.assign(numt, true);
primes[0] = false;
primes[1] = false;
long double sqrtt = sqrt(numt);
for(unsigned long long l = 0; l<=sqrtt; l++) {
if(!primes[l]) {
//cout << l << " is false" << endl;
continue;
}
for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
//cout << cl << ", a multiple of " << l << endl;
primes[cl] = false;
}
}
const double m = GetTickCount();
unsigned long long count = 0;
if(!skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
cout << l << endl;
count ++;
}
if(skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;
const double e = GetTickCount();
cout << endl;
cout << count << " primes less than or equal to " << numt-1 << endl;
cout << "Calculation took " << m-s << " ms";
if(!skipprint) cout << " and printing took " << e-m << " ms";
else cout << " and counting took " << e-m << " ms";
cout <<"." << endl;
//for each(bool b in primes) cout << b << endl;
return 0;
}