0

I am trying to create a function that takes an input 'n' and provides an output which is the highest Fibonacci number that's less than or equal to 'n'. For example, if n = 5, then output is 5. If n = 6, then output is 5.

My solution is workable but it does not seem "efficient" and I am looking for an alternative method. Here is what I did:

def fib(n):

    if n<0:
        print("Invalid input")
    x , y = 0 , 1
    while x <= n:
        x , y = y , y + x
    return abs(x-y)

I don't think that using abs(x-y) seems very efficient so I would like to ask if anybody has a different way to solving this problem. Thank you.

2 Answers2

0
def fib(n):
    if n<0:
        print("Invalid input")
    x , y = 0 , 1
    while x <= n:
        x , y = y , y + x
    return y - x
Jan Christoph Terasa
  • 5,781
  • 24
  • 34
0

This Solution for your question

def fib(n):
    x, y = 0, 1
    while True:
        x, y = y , x + y
        if x > n:
            return y-x

with this you get correct answer

Om trivedi
  • 32
  • 3