forked from AllAlgorithms/c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
is_prime.c
45 lines (35 loc) · 854 Bytes
/
is_prime.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
// Returns 1 if the given number is prime, 0 otherwise
int is_prime(unsigned long x) {
switch (x) {
case 0:
case 1:
return 0;
case 2:
return 1;
default: {
unsigned int i = 0;
// Multiples of 2 are not prime
if (0 == (x % 2)) {
return 0;
}
// Test odd numbers from 3 up to the square root of x
for (i = 3; (i * i) <= x; i += 2) {
if(0 == (x % i)) {
return 0;
}
}
return 1;
}
}
}
int main()
{
unsigned long x = 0;
while (1) {
printf("Provide an integer: \n");
scanf("%lu", &x);
printf("%lu is%s prime\n", x, is_prime(x) ? "" : " not");
}
return 0;
}