Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Play around with sieves and benchmarking...

Views: 276
Image: ubuntu2004
1
/*
2
emcc -O3 sieve.c -s EXPORTED_FUNCTIONS='["_pi"]' -s
3
EXPORTED_RUNTIME_METHODS='["ccall","cwrap"]'
4
5
Then:
6
7
> pi2 = require('./a.out.js').cwrap('pi', 'number', ['number']); {pi} =
8
require('./sieve.js') > t = new Date(); for(i=0;i<10;i++){pi2(1000000+i);} new
9
Date() - t; 71 > t = new Date(); for(i=0;i<10;i++){pi(1000000+i);} new Date() -
10
t; 559
11
*/
12
13
#include <stdio.h>
14
#include <malloc.h>
15
16
int pi(int number) {
17
int i, j;
18
19
int* primes = (int*)malloc(sizeof(int) * (number + 1));
20
21
for (i = 2; i <= number; i++) primes[i] = i;
22
23
i = 2;
24
while ((i * i) <= number) {
25
if (primes[i] != 0) {
26
for (j = 2; j < number; j++) {
27
if (primes[i] * j > number)
28
break;
29
else
30
// Instead of deleting , making elements 0
31
primes[primes[i] * j] = 0;
32
}
33
}
34
i++;
35
}
36
37
int cnt = 0;
38
for (i = 2; i <= number; i++) {
39
// If number is not 0 then it is prime
40
if (primes[i] != 0) {
41
cnt += 1;
42
}
43
}
44
45
free(primes);
46
47
return cnt;
48
}
49
50
int main() {
51
int j = 0;
52
for (int i = 0; i < 100; i++) {
53
j += pi(3 * 1000000);
54
printf('%d\n', j);
55
fflush(stdout);
56
}
57
printf("%d\n", j);
58
}
59
60