Skip to content

Instantly share code, notes, and snippets.

@stevenschmatz
Last active December 8, 2017 19:28
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 stevenschmatz/e72e7e4a966c5cfcc1cc4876777b4498 to your computer and use it in GitHub Desktop.
Save stevenschmatz/e72e7e4a966c5cfcc1cc4876777b4498 to your computer and use it in GitHub Desktop.
Exponential computation time of naive Fibonacci algorithm
from time import time
from typing import List
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def fibonacci_naive(n: int) -> int:
if n <= 2: return 1
return fibonacci_naive(n-1) + fibonacci_naive(n-2)
def fibonacci(n):
table = [1, 1]
while len(table) < n:
table.append(table[-1] + table[-2])
return table[-1]
def get_fibonacci_times(max_n: int, cache=True) -> List[int]:
times = []
for i in range(int(max_n / 100)):
start = time()
if cache: fibonacci(i * 100)
else: fibonacci_naive(i)
times.append(time() - start)
return times
def main():
times = get_fibonacci_times(35, cache=False)
print(times)
times = get_fibonacci_times(100000, cache=True)
print(times)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment