While26. An integer N (> 1) is given, which is the Fibonacci number: \(N = F_K\) (the definition of Fibonacci numbers is given in the exercise While24). Find the integers \(F_{K-1}\) and \(F_{K + 1}\) - the previous and the next Fibonacci numbers.

Solution in Python 3:

import random

fib = []

def Fib1(N):
if N < len(fib):
#print("Fast")
return fib[N-1]
if N == 1 or N == 2:
if N > len(fib):
fib.append(1)
return 1
#print("Slow")
y = Fib1(N-2) + Fib1(N-1)
if N > len(fib):
fib.append(y)
return y

K = random.randint(1,40)
#N = 4181
print("K = ",K)
N = Fib1(K)
print("Fibonacci Number (N): ", N)

F1 = F2 = 1
print(1,":",F1)
print(2,":",F2)
i = 2
while F1 < N:
F0, F1, F2 = F1, F2, F1+F2
i += 1
print(i,":",F1)
print()
print("{0} + {1} = {2}".format(F0,N,F2))