[prev] [index] [next]

Performance Example

Consider a program to test for prime numbers.

An integer n is prime if it has no divisors except 1 and n

Straightforward, literal, C implementation:

int is_prime(int n)
{
    int i, ndiv = 0;
    for (i = 1; i <= n; i++) {
        if (n % i == 0) ndiv++;
    }
    return (ndiv == 2);
}

By inspection, it's clearly correct. How about performance?