diff options
| author | tylov <[email protected]> | 2023-07-20 15:09:10 +0200 |
|---|---|---|
| committer | tylov <[email protected]> | 2023-07-20 15:12:29 +0200 |
| commit | 900295256d825fc323149cd223c49787f32a3696 (patch) | |
| tree | 6c79cf4209e3975bb6865e2940b9cb56ea469c73 /misc/examples/bitsets/prime.c | |
| parent | 224a04f7fa7549ed94d2a1415eb25829e39a7cca (diff) | |
| download | STC-modified-900295256d825fc323149cd223c49787f32a3696.tar.gz STC-modified-900295256d825fc323149cd223c49787f32a3696.zip | |
Moved examples to sub-directories. Added cotask1.c cotask2.c examples.
Diffstat (limited to 'misc/examples/bitsets/prime.c')
| -rw-r--r-- | misc/examples/bitsets/prime.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/misc/examples/bitsets/prime.c b/misc/examples/bitsets/prime.c new file mode 100644 index 00000000..cb3b095a --- /dev/null +++ b/misc/examples/bitsets/prime.c @@ -0,0 +1,56 @@ +#include <stdio.h> +#include <math.h> +#include <time.h> +#include <stc/cbits.h> +#include <stc/algo/filter.h> +#include <stc/algo/crange.h> + + +cbits sieveOfEratosthenes(int64_t n) +{ + cbits bits = cbits_with_size(n/2 + 1, true); + int64_t q = (int64_t)sqrt((double) n) + 1; + for (int64_t i = 3; i < q; i += 2) { + int64_t j = i; + for (; j < n; j += 2) { + if (cbits_test(&bits, j>>1)) { + i = j; + break; + } + } + for (int64_t j = i*i; j < n; j += i*2) + cbits_reset(&bits, j>>1); + } + return bits; +} + +int main(void) +{ + int n = 1000000000; + printf("Computing prime numbers up to %d\n", n); + + clock_t t = clock(); + cbits primes = sieveOfEratosthenes(n + 1); + int np = (int)cbits_count(&primes); + t = clock() - t; + + 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("\n"); + + puts("Show the last 50 primes using a temporary crange generator:"); + crange range = crange_make(n - 1, 0, -2); + + c_forfilter (i, crange, range, + cbits_test(&primes, *i.ref/2) && + c_flt_take(i, 50) + ){ + printf("%lld ", *i.ref); + if (c_flt_getcount(i) % 10 == 0) puts(""); + } + printf("Number of primes: %d, time: %.2f\n\n", np, (double)t/CLOCKS_PER_SEC); + + cbits_drop(&primes); +} |
