Check whether an integer is a prime number in C
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
Code:
/************************** \
* * xyz_abc1.c
/ * Algorithm: testing all 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, many iterations =% d \ n", nb, count);
else
printf ( "% d is not the first number, many iterations =% d \ n", nb, count);
return 0;
)
Dividing peers will not be tested, research is limited to odd dividers
Algorithm 2: Dividing peers will not be tested, research is limited to odd dividers
Code:
/************************** \
* * xyz_abc1.c
\ **************************/
/ * Algorithm: exclude even numbers and
* Test all 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, many iterations =% d \ n",
nb, count);
else
printf ( "% d is not the first number, many iterations =% d \ n", nb, count);
return 0;
)
Dividing up the odd square root of N will be tested
Algorithm 3: Dividing up the odd square root of N will be tested
Dividing up the odd square root of N will be tested
Code:
/************************** \
* * xyz_abc3.c
\ **************************/
/ * Algorithm: exclude even numbers and
* Test all dividers to the square root * /
# include <stdio.h>
# include <math.h>
int main (void)
(
int i, nb, count, test limits;
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, many iterations =% d \ n", nb, count);
else
printf ( "% d is not the first number, many iterations =% d \ n", nb, count);
return 0;
)