[prev] [index] [next]

Exercise: Prime Number Tester

Consider a function to test numbers for primality.

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

Implement, test, and examine performance. Tune, if necessary.