-
Notifications
You must be signed in to change notification settings - Fork 1
/
primes.c
56 lines (48 loc) · 1.17 KB
/
primes.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
46
47
48
49
50
51
52
53
54
55
56
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define SetBit(k) ( primes[(k/32)] |= (1 << (k%32)) )
#define TestBit(k) ( primes[(k/32)] & (1 << (k%32)) )
int main(int argc, char *argv[]) {
int* primes;
unsigned long int rootlim;
unsigned long int factor;
unsigned long int i;
unsigned long int lim;
if(argc<=1) {
printf("Please provide a number\n");
return 1;
}
lim = strtoul(argv[1], NULL, 0);
primes = malloc(lim + (2*sizeof(int)) - (lim % sizeof(int)));
if (primes == NULL) {
fprintf(stderr, "malloc failed\n");
return 1;
}
for (i = 0; i < (lim / sizeof(int)) + 1; i++) {
primes[i] = 0;
}
rootlim = sqrt(lim);
rootlim++;
factor = 0;
SetBit(0);
SetBit(1);
while (factor < rootlim) {
while (factor < lim) {
if (!TestBit(factor)) {
break;
}
factor++;
}
for (i = factor * factor; i < lim; i += factor) {
SetBit(i);
}
factor++;
}
for (i = 0; i < lim; i++) {
if (!TestBit(i)) {
printf("%lu\n", i);
}
}
return 0;
}