Skip to content

Instantly share code, notes, and snippets.

@seisvelas
Last active May 27, 2019 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seisvelas/67fe070e9fe3ed731c2abb67b388992f to your computer and use it in GitHub Desktop.
Save seisvelas/67fe070e9fe3ed731c2abb67b388992f to your computer and use it in GitHub Desktop.
All kinds of fibonacci solutions
#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)));
}
# 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