Possible Duplicates:
C - determine if a number is prime
Is there any way to test easily in C whether a selected number is prime or not?
The easiest way is writing a loop, like:
int is_prime(int num)
{
if (num <= 1) return 0;
if (num % 2 == 0 && num > 2) return 0;
for(int i = 3; i < num / 2; i+= 2)
{
if (num % i == 0)
return 0;
}
return 1;
}
You can then optimize it, iterating to floor(sqrt(num))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With