I know I can use Sieves to make this faster, but I wondered if there's anything I'm missing with this implementation of the "naive" algorithm.
On my PC running the command (first million primes):
g++ -std=c++11 -Wall -Wextra -Ofast primes.cpp -o primes && time ./primes 15485863
this takes approximately 9.3 secs.
#include <climits>
#include <string>
#include <vector>
typedef unsigned long long ull;
int main(int argc, char *argv[])
{
ull limit = ULLONG_MAX;
if (argc > 1) limit = std::stoi(argv[1]);
std::vector<ull> primes;
primes.push_back(2);
printf("2 is prime\n");
primes.push_back(3);
printf("3 is prime\n");
primes.push_back(5);
printf("5 is prime\n");
int inc = 2;
for (ull i = 7; i <= limit; i += inc) {
bool isprime = true;
for (ull j = 0; primes[j] * primes[j] <= i && j < primes.size(); j++) {
if (i % primes[j] == 0) {
isprime = false;
break;
}
}
if (isprime) {
printf("%llu is prime\n", i);
primes.push_back(i);
}
inc == 2 ? inc = 4 : inc = 2;
}
}