Created
June 9, 2019 12:41
-
-
Save jabernardo/9a437eba9965eef792e1ee09cfca844e to your computer and use it in GitHub Desktop.
Fibonacci Sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int fib(); | |
int main() { | |
// Normal | |
int term0 = 0, term1 = 0, term2 = 1; | |
printf("\n[Normal Method]\n"); | |
for (int i = 0; i < 10; i++) { | |
printf("%d ", term2); | |
term0 = term1; // 0, 1, 1, 2, | |
term1 = term2; // 1, 1, 2, 3, | |
term2 = term0 + term1; // 1, 2, 3, 5 | |
} | |
printf("\n[Recursive Method]\n"); | |
// Recursive | |
for (int i = 0; i < 10; i++) { | |
printf("%d ", fib(i)); | |
} | |
return 0; | |
} | |
int fib(int number) { | |
if (number < 2) | |
return number; | |
// 0 1 2 3 5 | |
// 0: 0 | |
// 1: 1 | |
// 2: (2 - 1 = 1) + (2 - 2 = 0) = 1 | |
// 3: (3 - 1 = 2: (2 - 1 = 1) + (2 - 2 = 1) = 1) + (3 - 2 = 1) = 2 | |
return fib(number - 1) + fib(number - 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment