TheAlgorithms-C/misc/prime.c

36 lines
569 B
C
Raw Normal View History

2018-03-24 04:08:21 +08:00
#include <math.h>
#include <stdio.h>
2017-10-19 16:38:10 +08:00
int isPrime(int x)
{
if (x == 2)
{
return 1;
}
if (x < 2 || x % 2 == 0)
{
return 0;
}
double squareRoot = sqrt(x);
for (int i = 3; i <= squareRoot; i += 2)
{
if (x % i == 0)
2017-10-19 16:38:10 +08:00
return 0;
}
return 1;
}
int main()
{
2017-10-19 16:38:10 +08:00
int a;
printf("Input a number to see if it is a prime number:\n");
scanf("%d", &a);
if (isPrime(a))
printf("%d is a prime number.\n", a);
else
printf("%d is not a prime number.\n", a);
return 0;
}