My Coding > Programming language > Python > Exercise > Python: Fibonacci numbers

Python: Fibonacci numbers

Fibonacci number

Fibonacci sequence is a very mysterious sequence of numbers which can be described by equation:

  • F0 = 0, F1 = 1,
  • Fn = Fn-1 + Fn-2

In this example, we will make a function, calculating Fibonacci number


def fibonacci(n):
    fib1, fib2 = 0, 1
    for i in range (2, n + 1):
        fib1, fib2 = fib2, fib1 + fib2
    return fib2;

Fibonacci sequence

We can print out Fibonacci sequence in cycle


n = 10

fib1, fib2 = 0, 1
print(fib1, fib2, end=' ') # 0 1 
for i in range(2, n+1):
    fib1, fib2 = fib2, fib1 + fib2
    print(fib2, end=' ') # 1 2 3 5 8 13 21 34 55

Bine equation for Fibonacci number

It is possible to use Bine equation for calculations:

  • Fn = [φn / √5 ] - []-mean rounding
  • φ = (1 + √5)/2


def fibonacci(n):
    return pow(2 << n, n + 1, (4 << 2 * n) - (2 << n) - 1) % (2 << n)

print(fibonacci(71)) # 308061521170129


Published: 2021-11-06 22:56:55
Updated: 2021-11-06 23:24:05

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.