Documentos de Académico
Documentos de Profesional
Documentos de Cultura
LAB 1
Dariev Alexei
1st algorithm
from time import time
import matplotlib.pyplot as plt
def fib1(n):
if n<2:
return n
else:
return fib1(n-1) + fib1(n-2)
print([fib1(n) for n in range(20)])
def exectime(f, n):
startTime = time()
f(n)
return time() - startTime
def inputstime(f, arg):
times = []
for n in arg:
times.append(exectime(f,n ))
return times
def plotforarg(f, arg, title):
plt.plot(arg, inputstime(f, arg))
plt.title(title)
plt.ylabel("time")
plt.xlabel("n")
plt.show()
plotforarg(fib1, range(1, 20), title="plot of time for 1st")
2nd algorithm
3rd
algorithm
from time import time
import matplotlib.pyplot as plt
def fib3(n):
i = 1
j = 0
k = 0
h = 1
while n > 0:
if n % 2 == 1:
t = j * h
j = i * h + j * k + t
i = i * k + t
t = h ** 2
h = 2 * k * h + t
k = k ** 2 + t
n = int(n / 2)
return j
def exectime(f, n):
startTime = time()
f(n)
return time() - startTime
def inputstime(f, arg):
times = []
for n in arg:
times.append(exectime(f,n ))
return times
Conclusion:
In this laboratory work we used 3 different algorithms for solving Fibonacci
sequences. As we see in our calculations, we can say that 3rd algorithm is the
fastest.