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

2
  • 3
    Does this answer your question? Efficient calculation of Fibonacci series Commented Feb 1, 2023 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 Commented Feb 1, 2023 at 17:26

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

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

1 Comment

This prints fib numbers less than n, not the first n numbers. This is however a good general technique

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.