summaryrefslogtreecommitdiffhomepage
path: root/examples/cbits_prime.c
diff options
context:
space:
mode:
authorTyge Løvset <[email protected]>2021-01-21 08:26:54 +0100
committerTyge Løvset <[email protected]>2021-01-21 08:26:54 +0100
commit50da396d04714a18fa087ebbd1f2316958dbd6bd (patch)
tree0349909bf35183e2eced05ca0d3ce909f700c23e /examples/cbits_prime.c
parent9473eae780011ef520066ddcd36bb555e8e616e4 (diff)
downloadSTC-modified-50da396d04714a18fa087ebbd1f2316958dbd6bd.tar.gz
STC-modified-50da396d04714a18fa087ebbd1f2316958dbd6bd.zip
Reverted namings: crand to crandom, and copt to coption.
Diffstat (limited to 'examples/cbits_prime.c')
-rw-r--r--examples/cbits_prime.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/examples/cbits_prime.c b/examples/cbits_prime.c
new file mode 100644
index 00000000..5c5d3969
--- /dev/null
+++ b/examples/cbits_prime.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+#include <stc/cbits.h>
+
+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