diff options
| author | Tyge Lovset <[email protected]> | 2022-12-20 23:31:51 +0100 |
|---|---|---|
| committer | Tyge Lovset <[email protected]> | 2022-12-20 23:31:51 +0100 |
| commit | 5f57d597cd27aef55adbcb3b452973b0c6e33667 (patch) | |
| tree | dfd59c2fd0e36a6ef37912a9d0cc5a65970f1524 /misc/examples/prime.c | |
| parent | 1763be8c8cbbc0896477fcf924edd4180d1345a9 (diff) | |
| download | STC-modified-5f57d597cd27aef55adbcb3b452973b0c6e33667.tar.gz STC-modified-5f57d597cd27aef55adbcb3b452973b0c6e33667.zip | |
Restructured folders: examples, benchmarks, tests into misc folder.
Diffstat (limited to 'misc/examples/prime.c')
| -rw-r--r-- | misc/examples/prime.c | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/misc/examples/prime.c b/misc/examples/prime.c new file mode 100644 index 00000000..287fb69b --- /dev/null +++ b/misc/examples/prime.c @@ -0,0 +1,51 @@ +#include <stdio.h> +#include <math.h> +#include <time.h> +#include <stc/cbits.h> +#include <stc/views.h> + +cbits sieveOfEratosthenes(size_t n) +{ + cbits bits = cbits_with_size(n/2 + 1, true); + size_t q = (size_t) sqrt((double) n) + 1; + for (size_t i = 3; i < q; i += 2) { + size_t j = i; + for (; j < n; j += 2) { + if (cbits_test(&bits, j>>1)) { + i = j; + break; + } + } + for (size_t j = i*i; j < n; j += i*2) + cbits_reset(&bits, j>>1); + } + return bits; +} + +int main(void) +{ + size_t n = 1000000000; + printf("computing prime numbers up to %" c_ZU "\n", n); + + clock_t t1 = clock(); + c_with (cbits primes = sieveOfEratosthenes(n + 1), cbits_drop(&primes)) { + puts("done"); + size_t np = cbits_count(&primes); + clock_t t2 = clock(); + + printf("number of primes: %" c_ZU ", time: %f\n", np, (t2 - t1) / (float)CLOCKS_PER_SEC); + puts("Show all the primes in the range [2, 1000):"); + printf("2"); + c_forrange (i, 3, 1000, 2) + if (cbits_test(&primes, i>>1)) printf(" %lld", i); + puts(""); + + puts("Show the last 50 primes using a temporary crange generator:"); + c_forfilter (i, crange, crange_literal(n - 1, 0, -2) + , cbits_test(&primes, *i.ref>>1) + , c_flt_take(i, 50)) { + printf("%lld ", *i.ref); + if (i.count % 10 == 0) puts(""); + } + } +} |
