diff options
| author | Tyge Løvset <[email protected]> | 2023-07-24 08:48:41 +0200 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-07-24 08:48:41 +0200 |
| commit | 374b3c27831cd4e09461867ed231669777b96951 (patch) | |
| tree | 88011006f6d536cdb1ad1eca8073392ca80687cc /misc/examples/bitsets/prime.c | |
| parent | 177418232a2d8a8b0df1667d3e4bd15dc37db59f (diff) | |
| parent | 650b053f443f9132dadb6d1ca924c0b36849739f (diff) | |
| download | STC-modified-374b3c27831cd4e09461867ed231669777b96951.tar.gz STC-modified-374b3c27831cd4e09461867ed231669777b96951.zip | |
Merge pull request #65 from stclib/dev43
Dev43
Diffstat (limited to 'misc/examples/bitsets/prime.c')
| -rw-r--r-- | misc/examples/bitsets/prime.c | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/misc/examples/bitsets/prime.c b/misc/examples/bitsets/prime.c new file mode 100644 index 00000000..7e5a2b3f --- /dev/null +++ b/misc/examples/bitsets/prime.c @@ -0,0 +1,58 @@ +#include <stdio.h> +#include <math.h> +#include <time.h> +#include <stc/cbits.h> +#include <stc/algorithm.h> + +typedef long long llong; + +cbits sieveOfEratosthenes(llong n) +{ + cbits bits = cbits_with_size(n/2 + 1, true); + llong q = (llong)sqrt((double) n) + 1; + for (llong i = 3; i < q; i += 2) { + llong j = i; + for (; j < n; j += 2) { + if (cbits_test(&bits, j>>1)) { + i = j; + break; + } + } + for (llong j = i*i; j < n; j += i*2) + cbits_reset(&bits, j>>1); + } + return bits; +} + +int main(void) +{ + llong n = 100000000; + printf("Computing prime numbers up to %lld\n", n); + + clock_t t = clock(); + cbits primes = sieveOfEratosthenes(n + 1); + + llong np = cbits_count(&primes); + t = clock() - t; + + printf("Number of primes: %lld, time: %f\n\n", np, (double)t/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("\n"); + + puts("Show the last 50 primes using a temporary crange generator:"); + crange range = crange_init(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(""); + } + + cbits_drop(&primes); +} |
