Está en la página 1de 4

APA

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

from time import time


import matplotlib.pyplot as plt
def fib2(n):
i = 1
j = 0
for k in range(1, n+1):
j = i + j
i = j - i
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
def plotforarg(f, arg, title):
plt.plot(arg, inputstime(f, arg))
plt.title(title)
plt.ylabel("time")
plt.xlabel("n")
plt.show()

plotforarg(fib2, range(1000000, 2000000, 5000), title="plot of time for 2nd")

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

def plotforarg(f, arg, title):


plt.plot(arg, inputstime(f, arg))
plt.title(title)
plt.ylabel("time")
plt.xlabel("n")
plt.show()
plotforarg(fib3, range(1000000, 2000000, 5000), title="plot of time for 3rd")

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.

También podría gustarte