Last active
May 27, 2019 22:36
-
-
Save seisvelas/67fe070e9fe3ed731c2abb67b388992f to your computer and use it in GitHub Desktop.
All kinds of fibonacci solutions
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> | |
#include <stdlib.h> | |
struct fib_node { | |
int n; | |
struct fib_node *left, *right; | |
}; | |
struct fib_node* fib(int n) { | |
struct fib_node *node; | |
node = malloc(sizeof(struct fib_node)); | |
node->n = n; | |
if (n && (n - 1)) { | |
node->left = fib(n-1); | |
node->right = fib(n-2); | |
} | |
return node; | |
} | |
int count_leaves(struct fib_node *node) { | |
if (node->left && node->right) { | |
return count_leaves(node->left) + | |
count_leaves(node->right); | |
} | |
return node->n; | |
} | |
void main(void) { | |
// displays 13, the 7th fib number | |
printf("%d\n", count_leaves(fib(7))); | |
} |
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
# fib using recursive generator | |
def fibgen(n, a=0, b=1): | |
yield a | |
if n > 0: | |
yield from fibgen(n-1, b, a+b) | |
def fib(n): | |
return list(fibgen(n))[n] | |
print(fib(7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment