So, a couple of things...
The main problem is that you're breaking out of your loop early whether the number is divisible by i
or not:
if ( num % i == 0 )
break;
else
break;
You only want to break out of the loop early if the number is evenly divisible by i
; otherwise, you check the against the next value of i
:
for ( i = 2 ; i < number/2; i++ )
{
if ( num % i == 0 )
break;
}
After the loop, check to see if i
is less than number / 2
; if it is, then number
is not prime:
if ( i < number / 2 )
// number is not prime
else
// number is prime
There are a couple of ways you can speed up your primality test. First of all, you only need to test up to the square root of number
, rather than number / 2
. Secondly, you can eliminate checks against even numbers; if a number is divisible by 2
, then it's divisible by any even number, so you only need to check against 2
once. In code:
int prime = 0; // initially false
if ( number == 2 ) // 2 is a special case, check separately
{
prime = 1;
}
else if ( number < 2 || number % 2 == 0 )
{
prime = 0; // negative numbers, 0, 1, and even numbers are not prime
}
else
{
prime = 1; // assume prime to begin with
for ( int i = 3; prime && i * i < number; i += 2 ) // continue while prime is true
{ // and i is less than sqrt(number)
prime = number % i;
}
}
printf( "%d is%s prime\n", number, prime ? "" : " not" );