Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Last active August 8, 2019 17:24
Show Gist options
  • Save mikamboo/eb9843f23b438e128ca23447e47db5be to your computer and use it in GitHub Desktop.
Save mikamboo/eb9843f23b438e128ca23447e47db5be to your computer and use it in GitHub Desktop.
Cached Fibonacci implementations
Map<int, int> cache = new Map();
int fibo(int n){
if(cache.containsKey(n))
{
return cache[n];
}
int result;
if(n == 0) {
result = cache[0] = 1;
return result;
}
if(n == 1) {
result = cache[1] = 1;
return result;
}
result = fibo(n-2) + fibo(n-1);
cache[n] = result;
return result;
}
void main() {
for (int i = 0; i < 10; i++) {
print('N=${i} : ${fibo(i + 1)}');
}
}
#!/usr/bin/python
cache = {}
def fibo(n):
if n == 0: return 1
if n == 1: return 1
result = 0
if n in cache:
result = cache[n]
else:
result = fibo(n-1) +fibo(n-2)
cache[n] = result
return result
for x in range(350):
print(fibo(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment