Damn no wonder that code was slow, cout is being called in the loop
#include <iostream>
#include <cmath>
#include <ctime>
#include <fstream>
#include <vector>
bool isPrimeSuperOptimized(long long number)
{
if (number < 2) return false;
if (number == 2) return true;
if (number == 3) return true;
if (number == 5) return true;
if (!(number % 2)) return false;
if (!(number % 3)) return false;
if (!(number % 5)) return false;
if (number < 7*7) return true;
int step[] = {7,11,13,17,19,23,29,31};
int sentry = (int)sqrt((double)number);
for(int r = 0; r < sentry; r += 30)
for(int i = 0; i < 8; ++i)
if (!(number % (r+step[i])))
return false;
return true;
}
int main()
{
std::cout.sync_with_stdio(false);
std::vector<long long> primes;
long long number = 10000000;
std::clock_t startfunction3;
double function3;
startfunction3 = std::clock();
for(int i = 2; i < number; i++)
{
if(isPrimeSuperOptimized(i))
{
std::cout << i << " ";
primes.push_back(i);
}
}
function3 = ( std::clock() - startfunction3 ) / (double)CLOCKS_PER_SEC;
std::cout << "\nFinished: " << function3;
std::cout << "\nAdding to list: ";
long long primesize = primes.size();
std::ofstream file;
file.open("primes.txt");
for(int i = 0; i < primesize; i++)
{
file << primes[i] << std::endl;
}
return 0;
}
Running primes up to 10,000,000 and then adding them to vector then a file after.
Thing is if I run this without the line "std::cout.sync_with_stdio(false);" I get somewhere around 95 run time.
If I run with that line, I get 6 run time
lol obviously this wouldnt be a real problem in an actual system because youre not printing them to the screen so youre saving energy without calling cout, but eesh thats a huge difference and really bad one too