summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRichard Braun <rbraun@sceen.net>2017-03-23 20:27:21 +0100
committerRichard Braun <rbraun@sceen.net>2017-03-23 20:35:46 +0100
commit15576a20c5b77517c816d34cbbe492d35fc8e8ad (patch)
tree9aa9095e313e23fa9aceb5439e6f87a91ccf5323
Initial commit
OK, I'm late, sue me.
-rw-r--r--Makefile18
-rw-r--r--main.c52
2 files changed, 70 insertions, 0 deletions
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..5ec3953
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,18 @@
+CC = gcc
+CFLAGS = \
+ -Wall -Wmissing-prototypes -Wstrict-prototypes \
+ -D _GNU_SOURCE -O2 -std=gnu11 -ggdb3
+
+BINARY = cpiday
+OBJECTS = main.o
+
+$(BINARY): $(OBJECTS)
+ $(CC) -o $@ $^ -lm
+
+%.o: %.c
+ $(CC) $(CFLAGS) -c -o $@ $<
+
+clean:
+ rm -f $(BINARY) $(OBJECTS)
+
+.PHONY: clean
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..876efc9
--- /dev/null
+++ b/main.c
@@ -0,0 +1,52 @@
+/*
+ * Celebrate Pi day in C.
+ *
+ * See https://www.youtube.com/watch?v=RZBhSi_PwHU to watch Matt Parker
+ * do it the hard way.
+ */
+
+#include <math.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+#define NR_PAIRS 1000000
+
+static unsigned int
+gcd(unsigned int a, unsigned int b)
+{
+ unsigned int tmp;
+
+ while (b != 0) {
+ tmp = b;
+ b = a % b;
+ a = tmp;
+ }
+
+ return a;
+}
+
+static bool
+coprimes(unsigned int a, unsigned int b)
+{
+ return (gcd(a, b) == 1);
+}
+
+int
+main(int argc, char **argv)
+{
+ unsigned int i, total;
+ double pi;
+
+ srand(time(NULL));
+
+ for (i = 0, total = 0; i < NR_PAIRS; i++) {
+ if (coprimes(rand(), rand())) {
+ total++;
+ }
+ }
+
+ pi = sqrt(6. * NR_PAIRS / total);
+ printf("%f\n", pi);
+}