Home > database >  program to find fibonacci sequence of a number
program to find fibonacci sequence of a number

Time:02-02

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

CodePudding user response:

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)

CodePudding user response:

n = 10
a, b = 0, 1
while a <= n:
    print(a)
    a, b = b, a   b

CodePudding user response:

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)
  • Related