[C language]Checking whether an integer is a prime number
Definition of a prime number
A prime number is an integer, which is divided only by 1 and itself.
Algorithm 1: dividers between 2 and N-1 will be tested
/**************************\
* prime_number1.c *
\**************************/
/* algorithm : test all the dividers */
#include <stdio.h>
int main (void)
{
int i, nb, count, test;
test = count = 0;
printf ("enter integer: ");
if (scanf ("%d", &nb) != 1)
return -1;
for (i = 2; i < nb; i++, count++)
if (nb % i == 0)
test = 1;
if (!test)
printf ("%d prime number, number of iterations = %d\n", nb, count);
else
printf ("%d is not a prime number, number of iterations = %d\n", nb,count);
return 0;
}
Algorithm 2: Even dividers will not be tested, research is limited to odd dividers
/**************************\
* prime_number2.c *
\**************************/
/* algorithm : exclude even numbers and
* test all the dividers */
#include <stdio.h>
int main (void)
{
int i, nb, count, test;
test = count = 0;
printf ("enter integer: ");
if (scanf ("%d", &nb) != 1)
return -1;
if (nb % 2 == 0)
test = 1;
else{
for (i = 3 ; i < nb; i+=2, count++)
if (nb % i == 0)
test = 1;
}
if (!test)
printf ("%d prime number, number of iterations = %d\n",
nb, count);
else
printf ("%d is not a prime number, number of iterations = %d\n",nb, count);
return 0;
}
Algorithm 3: All odd dividers up to the square root of N will be tested
/**************************\
* prime_number3.c *
\**************************/
/* algorithm : exclude all even numbers and
* test all the dividers up to square root */
#include <stdio.h>
#include <math.h>
int main (void)
{
int i, nb, count, test,limit;
test = count = 0;
printf ("enter integer : ");
if (scanf ("%d", &nb) != 1)
return -1;
limit = sqrt(nb) + 1;
if (nb % 2 == 0)
test = 1;
else{
for (i = 3 ; i < limit; i+=2, count++)
if (nb % i == 0)
test = 1;
}
if (!test)
printf ("%d prime number, number of iterations = %d\n", nb, count);
else
printf ("%d not a prime number, number of iterations = %d\n",nb, count);
return 0;
}
Algorithme4: stop the program when a divider is found
/**************************\
* prime_number4.c *
\**************************/
/* algorithm : exclude all even numbers and
* test all dividers up to the square root
* exit loop when first divider is found */
#include <stdio.h>
#include <math.h>
int main (void)
{
int i, nb, count, test,limit;
test = count = 0;
printf ("Enter integer: ");
if (scanf ("%d", &nb) != 1)
return -1;
limit = sqrt(nb) + 1;
if (nb % 2 == 0)
test = 1;
else{
for (i = 3 ; i < limit && ! test; i+=2, count++)
if (nb % i == 0)
test = 1;
}
if (!test)
printf ("%d prime number, number of iterations = %d\n", nb, count);
else
printf ("%d not prime number, number of iterations = %d\n", nb, count);
return 0;
}