1

how do i find the fibonacci sequence of a number . Here Is The code

def fib(n):
    for i in range(n):
        b = 1 
        
        b+=i
        print(b)
        
p = fib(9)

the program just returns the normal sum. how to do this in the easy way

  • 3
    Does this answer your question? [Efficient calculation of Fibonacci series](https://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series) – Michael Ruth Feb 01 '23 at 17:23
  • 1
    You're setting `b` to 1 in each iteration of the loop, rather than taking into account the new, updated `b` – G. Anderson Feb 01 '23 at 17:26

3 Answers3

3

The fibonacci sequence is built by adding the last two values of the sequence, starting with 1,1 (or 0,1 for the modern version). A recursive function does it elegantly:

def fib(n,a=1,b=1): 
    return a if n==1 else fib(n-1,b,a+b)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0
n = 10
a, b = 0, 1
while a <= n:
    print(a)
    a, b = b, a + b
JonSG
  • 10,542
  • 2
  • 25
  • 36
Fat Meh
  • 1
  • 1
  • This prints fib numbers less than n, not the first n numbers. This is however a good general technique – JonSG Feb 01 '23 at 17:44
0

try this using recursion

def fibonacci(n):
  if n <= 0:
    return 0
  elif n == 1:
    return 1
  else:
    return fibonacci(n-1) + fibonacci(n-2)