This is the code for returning two consecutive numbers of Fibonacci series whose product is passed in fib()
function. If the product exceeds the given number, the code ends by returning those two numbers and False
in the list
as shown.
This takes a huge time to run for larger numbers. Can someone help me with the optimization of this code?
def fib(n):
if n<=1:
return n
else:
return fib(n-1) + fib(n-2)
def productFib(prod):
i = 0
while i >= 0:
a = fib(i)*fib(i+1)
if a == prod:
return [fib(i), fib(i+1), True]
elif a > prod:
return [fib(i), fib(i+1), False]
i+=1
print(productFib(41)) # [8, 13, False]
print(productFib(40)) # [5, 8, True]
print(productFib(4895)) # [55, 89, True]
print(productFib(5895)) # [89, 144, False]
Fibonacchi series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... .