summaryrefslogtreecommitdiff
path: root/p2/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'p2/main.c')
-rw-r--r--p2/main.c51
1 files changed, 51 insertions, 0 deletions
diff --git a/p2/main.c b/p2/main.c
new file mode 100644
index 0000000..b2d2a45
--- /dev/null
+++ b/p2/main.c
@@ -0,0 +1,51 @@
+/*
+ * Each new term in the Fibonacci sequence is generated by adding the
+ * previous two terms. By starting with 1 and 2, the first 10 terms will be:
+ *
+ * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+ *
+ * By considering the terms in the Fibonacci sequence whose values do not
+ * exceed four million, find the sum of the even-valued terms.
+ */
+
+#include <stdio.h>
+#include <math.h>
+
+ #include "utils.h"
+
+// /* http://www.evanmiller.org/mathematical-hacker.html */
+// long int fib(unsigned long int n)
+// {
+// return lround((pow(0.5 + 0.5 * sqrt(5.0), n) -
+// pow(0.5 - 0.5 * sqrt(5.0), n)) / sqrt(5.0));
+// }
+
+// /* http://blog.noblemail.ca/2013/01/on-calculating-fibonacci-numbers-in-c.html */
+// long int fib2(unsigned long int n)
+// {
+// return lround((pow(0.5 + 0.5 * sqrt(5.0), n)) / sqrt(5.0));
+// }
+
+int main(int argc, char **argv)
+{
+ int i = 0;
+ int last = 0;
+ int sum = 0;
+
+ last = fib(2);
+
+ for (i = 3; last <= 4000000; i++)
+ {
+ /* even, if the lsb is 0 */
+ if (!(last & 1))
+ {
+ sum += last;
+ }
+
+ last = fib(i);
+ }
+
+ printf("result: %d\n", sum);
+
+ return 0;
+}