-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimes.c
More file actions
45 lines (36 loc) · 741 Bytes
/
primes.c
File metadata and controls
45 lines (36 loc) · 741 Bytes
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
/*
EXAMPLE: primes.c
implementation of the famous sieve of eratosthenes algorithm
using my C dialect
*/
int main() {
int N;
printf("Enter N: ");
scanf("%d", &N);
if (N < 2) {
printf("N must be greater than 1\n");
return 1;
}
// allocate aray of N boolean values, all set to false
bool *A = (bool *)malloc(N * sizeof(bool));
int i;
int max = (int)sqrt((float)N);
for (i = 2; i <= max; i++) {
if (!A[i]) {
int j = i * i;
while (j <= N) {
A[j] = true; // A[j] is not prime
j = j + i;
}
}
}
// find all values in the array still set to false
for (i = 2; i < N; i++) {
if (!A[i]) {
printf("%d ", i);
}
}
printf("\n");
free(A);
return 0;
}