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

Generation of Prime Numbers

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

Problem

I have created this prime number generator. I want it to be as fast as possible, but I am wondering if there is a faster way (there must be).

#include 
#include 
#include 

bool is_prime(const unsigned long long);

int
main(
    void)
{
    puts("2\n3");

    for (unsigned long long n = 5; n  1;
    } else if (n % 2 == 0 || n % 3 == 0) {
        return false;
    } else {
        for (unsigned long i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) {
                return false;
            }
        }

        return true;
    }
}


Possible slow areas:

  • usage of printf



  • usage of bool instead of int (not sure)



Compilation command:

clang -O3 -Weverything -pipe -march=native -o png png.c

Solution

Neither printf() nor bool would cause a significant performance impact. One reason could be that you're looping through a huge number which, depending on the system, could be as low as 18446744073709551615. Doing so in serial would likely take a long time for such a range, and you can always consider adding parallelization where feasible.

Beyond that, any slowdown would be in is_prime(). Not only are there are a few conditionals, which could involve slowdown from branch prediction, but there's another loop that could take a while. You may consider looking for pre-existing prime algorithms elsewhere, which could be faster than yours. That should help improve runtime considerably.

Context

StackExchange Code Review Q#113331, answer score: 2

Revisions (0)

No revisions yet.