So, I felt that many times people need a function to tell if a number is prime or not. Especially students. I have seen some relevant code in the forum to.
But, I saw that people of my level and even higher provided algorithms that were not so efficient in my mind. Probably they didn't try enough to improve their implementations.
So, I decided to write my function isPrime. If someone sees some way of improvement, then I would very glad˛ if he or she let me know!!
I have uploaded the function to my corner of the web.
But, for those that do not really like the css of my corner, I post the code here as well :)
Code:#include <stdio.h>
#include <math.h>
int isPrime(const int);
int main(void)
{
int i;
for (i = 1 ; i <= 15 ; ++i)
printf("%d is %sprime\n", i, isPrime(i) ? "" : "NOT ");
return 0;
}
int isPrime(const int number)
{
int i, r, prime = 1;
if (number != 2 && number % 2 == 0)
prime = 0;
else
for (i = 3, r = sqrt(number) ; i <= r && prime ; i += 2)
if (number % i == 0)
prime = 0;
return prime;
}