From c8a7b59dcc8a1d6cd7bf5f5bc6b76f26a97b34d6 Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Mon, 29 Mar 2021 14:27:14 +0200 Subject: Another update of cbits. --- examples/cbits_prime.c | 39 --------------------------------------- examples/prime.c | 27 ++++++++++++--------------- 2 files changed, 12 insertions(+), 54 deletions(-) delete mode 100644 examples/cbits_prime.c (limited to 'examples') diff --git a/examples/cbits_prime.c b/examples/cbits_prime.c deleted file mode 100644 index e2e7877a..00000000 --- a/examples/cbits_prime.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include - -static inline cbits sieveOfEratosthenes(size_t n) -{ - cbits primes = cbits_with_size(n + 1, true); - cbits_reset(&primes, 0); - cbits_reset(&primes, 1); - - c_forrange (i, size_t, 2, n+1) { - // If primes[i] is not changed, then it is a prime - if (cbits_test(primes, i) && i*i <= n) { - c_forrange (j, size_t, i*i, n+1, i) { - cbits_reset(&primes, j); - } - } - } - return primes; -} - - -int main(void) -{ - int n = 100000000; - printf("computing prime numbers up to %u\n", n); - - cbits primes = sieveOfEratosthenes(n); - puts("done"); - - size_t np = cbits_count(primes); - printf("number of primes: %zu\n", np); - - printf("2 "); - c_forrange (i, int, 3, 1001, 2) { - if (cbits_test(primes, i)) printf("%d ", i); - } - puts(""); - cbits_del(&primes); -} \ No newline at end of file diff --git a/examples/prime.c b/examples/prime.c index f11f1627..39418c49 100644 --- a/examples/prime.c +++ b/examples/prime.c @@ -5,40 +5,37 @@ cbits sieveOfEratosthenes(size_t n) { - cbits bits = cbits_with_pattern(n, 0xAAAAAAAAAAAAAAAA); - size_t q = sqrt(n); - cbits_reset(&bits, 1); - cbits_set(&bits, 2); + cbits bits = cbits_with_size(n>>1, true); + size_t q = (size_t) sqrt(n); - for (size_t j, i = 3; i <= q; i += 2) { - for (j = i; j < n; j += 2) { - if (cbits_test(bits, j)) { + for (size_t i = 3; i <= q; i += 2) { + for (size_t j = i; j < n; j += 2) { + if (cbits_test(bits, j>>1)) { i = j; break; } } - for (j = i*i; j < n; j += i*2) - cbits_reset(&bits, j); + for (size_t j = i*i; j < n; j += i*2) + cbits_reset(&bits, j>>1); } return bits; } - int main(void) { size_t n = 100000000; - printf("computing prime numbers up to %u\n", n); + printf("computing prime numbers up to %zu\n", n); clock_t t1 = clock(); cbits primes = sieveOfEratosthenes(n + 1); size_t np = cbits_count(primes); clock_t t2 = clock(); - printf("number of primes: %zu, time: %f\n", np, (t2 - t1)/(float)CLOCKS_PER_SEC); + printf("number of primes: %zu, time: %f\n", np, (t2 - t1) / (float)CLOCKS_PER_SEC); - for (size_t i=0; i<=1000; ++i) - if (cbits_test(primes, i)) printf("%d ", i); + printf(" 2"); for (size_t i = 3; i < 1000; i += 2) + if (cbits_test(primes, i>>1)) printf(" %zu", i); puts(""); cbits_del(&primes); -} \ No newline at end of file +} -- cgit v1.2.3