Andrew Tsay
Andrew Tsay

Reputation: 1953

Simple Fibonacci sequence not ouputting correct answer in Python

Here's a very simple script, yet when you call the function with any number, it turns out wrong.

def fib(n):
     a=0
     b=1
     while a < n:
         a, b = b, a+b
     print(a)

fib(10) = 13. Which is wrong.

Upvotes: 0

Views: 289

Answers (1)

Soulan
Soulan

Reputation: 391

def fib(n):
     a=0
     b=1
     i=1
     while i < n:
        a, b = b, a+b
        i+=1
     print(b)

try this ^^

you can not use a because a is not rising linear, it is rising depending on your current fibonacci calculation status... so you need an extra counter for taking in what step you are

Upvotes: 2

Related Questions