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
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
Joseph Green
  • 31
  • 1
  • 4
  • 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. – Carlos Horn Dec 10 '22 at 08:55

2 Answers2

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)))
bigbounty
  • 16,526
  • 5
  • 37
  • 65
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)

Thomas Dussaut
  • 728
  • 1
  • 7
  • 20
  • 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. – Thierry Lathuille Feb 26 '19 at 10:25
  • 1
    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. – PatrickT Jun 27 '21 at 00:01