Joseph Green
Joseph Green

Reputation: 31

Fibonacci Sequence In Python (Most Efficient)

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

Upvotes: 0

Views: 8223

Answers (2)

bigbounty
bigbounty

Reputation: 17368

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

Upvotes: 3

Thomas Dussaut
Thomas Dussaut

Reputation: 746

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)

Upvotes: 2

Related Questions