summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo.khan@gmail.com>2020-08-12 10:23:43 -0600
committermo khan <mo.khan@gmail.com>2020-08-12 10:23:43 -0600
commitcd22ec7ce90f22924931173e086d57380e0180b9 (patch)
tree767d6c7716d4325a3d5e828d34d3ef7f872cc58e
parent031491a0f79295b134a2aa14ebb82bdbfb6efac5 (diff)
Add notes on fibonacci sequence
-rw-r--r--README.md39
-rw-r--r--fib.c26
2 files changed, 55 insertions, 10 deletions
diff --git a/README.md b/README.md
index e93e732..8463bc1 100644
--- a/README.md
+++ b/README.md
@@ -184,6 +184,13 @@ Workbench
* terminal:
+* variable declaration
+* assignment
+* conditional expression
+* loops
+* functions
+* structs / data
+
# Version Control
- Version (1 - many)
@@ -192,13 +199,43 @@ Workbench
# Recursion
The Fibonacci numbers are the numbers in the following integer sequence.
-0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
+
+|0|1|2|3|4|5|6| 7| 8| 9|10|11| 12|
+---------------
+|0|1|1|2|3|5|8|13|21|34|55|89|144| ...
+
+12th number
+
+n = 12
+n - 1 = 11
+n - 2 = 11
+
+n0 = 0
+n1 = 1
+n = (n-1) + (n-2)
+
+144 = 89 + 55
```plaintext
Fn = Fn-1 + Fn-2
F0 = 0 and F1 = 1
```
+How to solve a problem?
+
+1. Understand the problem
+2. Pick a solution
+3. Implement
+4. Review
+
+Test Driven Development/Design
+
+1. Red -> failing testing
+2. Green -> make it pass, be responsible
+3. Refactor -> reflect. can we improve this?
+ * time/space complexity
+ * program design
+
Problem:
Given a number n, print n-th Fibonacci Number.
diff --git a/fib.c b/fib.c
index 7525d1b..fffd94f 100644
--- a/fib.c
+++ b/fib.c
@@ -1,26 +1,34 @@
#include <stdio.h>
#include <assert.h>
+// 1. base case -> ends the loops
+// 2. recurrence
int fib(int n)
{
- if (n == 1) {
- return 0;
+ if (n <= 1) {
+ printf("%d: %d + %d = %d\n", n, n, n + n);
+ return n;
}
- if (n == 2 || n == 3) {
- return 1;
- }
+ int y = fib(n - 2);
+ int x = fib(n - 1);
+ printf("%d: %d + %d = %d\n", n, x, y, x+y);
- return 2;
+ return x + y;
}
int main(int argc, char *argv[])
{
- assert(fib(1) == 0);
+ assert(fib(-2) == 0);
+ assert(fib(-1) == 0);
+ assert(fib(0) == 0);
+ assert(fib(1) == 1);
assert(fib(2) == 1);
- assert(fib(3) == 1);
- assert(fib(4) == 2);
+ assert(fib(3) == 2);
+ assert(fib(4) == 3);
+ assert(fib(12) == 144);
+ printf("%d\n", fib(100));
printf("YAY!\n");
return 0;