Prime Optimization

I was writing a piece of code to find all primes in a certain number range, and I came up with this to check if a number was a prime. Now, it takes about 20 seconds to get to a million on an Intel Atom processor (this is on my netbook) but I was still wondering how I could make it faster. I certainly can't think of any ways to make it faster.

1
2
3
4
5
6
7
8
9
10
11
bool isPrime(unsigned int num) {
    if ((num % 2) == 0) {
        return 0;
    }
    for (int i = 3;i<=sqrt(num);i+=2) {
        if ((num % i) == 0){
        return 0;
        }
    }
    return 1;
}
Last edited on
One optimization for your code:
cache the value of sqrt(num) so it is not recalculated for every loop. Although I think the compiler might have done something similar, still doesn't hurt to do that.

Another option is to use a prime sieve.
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Advantage: Only one calculation is done per number to determine if it is prime and further queries are done in constant time

Disadvantage: Uses more memory and the range of numbers the user can check is limited by the amount of memory available to the program
Topic archived. No new replies allowed.