0

Anyone know the most efficient way of displaying the first 100 numbers in the Fibonacci Sequence in Python please?

Here is my current code:

fib1,fib2,fib3= 0,0,1  

while fib3< 100: 
    print(fib3) 
    fib1=fib2 
    fib2=fib3
    fib3=fib1 + fib2
1
  • 1
    Please avoid asking for superlatives (most efficient). You can tune algorithms on execution speed, memory consumption, energy consumption, etc. The most efficient solution to your problem could be a table lookup of pre computed values. Commented Dec 10, 2022 at 8:55

2 Answers 2

3

Understand the working of python and fibonacci Sequence. Use generator feature of python. Follow the code

a = int(input('Give num: '))

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fib(a)))
Sign up to request clarification or add additional context in comments.

Comments

2
from math import sqrt
def F(n):
    return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))

According to the Fibonacci formula, here's a way to get the nth member of the Fibonacci sequence.

This function doesn't use loops nor recursion (recursions are horrible in Python, they are always slower than an iterative solution, because of how Python handle recursion, see here for more info about it)

2 Comments

This doesn't return integer values because of rounding errors on the floats, and is much slower than just building the list with a loop :out = [1, 1] ; for i in range(n-2): out.append(out[-1]+out[-2]) is 9 times faster for 100 values according to my timing.
This is the Binet formula: Fibonacci introduced the recursive approach, not the closed-form formula. It should be faster than the recursive approach. Taking a round or (better) an int of the return value adds a little cost. There are faster methods, but this is among the fast ones.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.