If the number you are looking for is relatively small, then you can also use the sieve of eratosthenes.
Otherwise, there are some small optimizations you can make to the algorithm.
Check for division by 2, 3, 5, and 7. If none are factors, then you only
need to check subsequent numbers that end in 1, 3, 7, or 9 (eg, 11, 13, 17, 19,
21, 23, 27, 29).
So I'd do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
//pseudo-code
if( num is divisble by 2, 3, 5, or 7 )
output "not prime";
exit;
unsigned long root = static_cast<unsigned long>( sqrt( num ) );
for( unsigned long base = [10...root] counting by 10 )
if( num is divisible by base + 1 OR
num is divisible by base + 3 OR
num is divisible by base + 7 OR
num is divisible by base +9 )
output "not prime"
exit;
end for
|