viewing paste myPrimeFunc | C++

Posted on the | Last edited on
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
#include <iostream>
#include <iomanip>
#include <cmath>
 
#define START 1
#define STOP 10000000
#define PRECISION 10
 
using namespace std;
 
bool myPrimeFunc(unsigned n){
       
        unsigned end = sqrt(n);
       
        if (n%2 == 0 || n%3 == 0 || n%5 == 0 || n%7 == 0)
                return false;
       
        for(unsigned i = 11; i <= end; i += 2 )
                if(n%i == 0)
                        return false;
       
        return true;
       
}
 
int main () {
        float totalTime = 0;
        for(int n = 0; n < PRECISION; n++){
                int startTime = clock();
                int primeCount = 0;
                cout << "Initiated Prime Search.." << endl;
                for(unsigned i = START; i < STOP; i++ ){
                        if(i == 2 || i == 3 || i == 5 || i == 7)
                                primeCount++;
                        else if(myPrimeFunc(i)){
                                //cout << i << " is a prime."<< endl; //print each result
                                primeCount++;
                        }
               
                }
                cout << "Found a total of: " << primeCount << " Prime Numbers." << endl;
                cout << "Ended in " << setprecision(9) << fixed << (float)(clock() - startTime)/CLOCKS_PER_SEC << " seconds." << endl;
                totalTime += (float)(clock() - startTime)/CLOCKS_PER_SEC;
        }
       
        cout << "\nTotal time: " << totalTime;
        cout << "\nAverage time: " << totalTime/PRECISION;
 
        return 0;
}
 
Viewed 503 times, submitted by Streusel.