Skip to content

Instantly share code, notes, and snippets.

@jabernardo
Created June 9, 2019 12:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jabernardo/9a437eba9965eef792e1ee09cfca844e to your computer and use it in GitHub Desktop.
Save jabernardo/9a437eba9965eef792e1ee09cfca844e to your computer and use it in GitHub Desktop.
Fibonacci Sequence
#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