patterncMinor
Generation of Prime Numbers
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).
Possible slow areas:
Compilation command:
#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
boolinstead ofint(not sure)
Compilation command:
clang -O3 -Weverything -pipe -march=native -o png png.cSolution
Neither
Beyond that, any slowdown would be in
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.