HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Find primes using "naive" algorithm

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
naiveprimesalgorithmusingfind

Problem

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 
#include 
#include 
#include 

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 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;
    }
}

Solution

A quick detail

You've written inc == 2 ? inc = 4 : inc = 2; : this is not the ""right"" way to use the "ternary" operator. Don't get me wrong, it will do what you expect it to do. However, the whole point of the operator is to return a value. In your case, it is no different that : if (inc == 2) inc = 4; else inc = 2;.

This calls for a ternary operator but to write it in a simple way : inc = (inc == 2) ? 4 : 2;

Context

StackExchange Code Review Q#66636, answer score: 12

Revisions (0)

No revisions yet.