Ad

This implementation of fibonacci follows https://www.nayuki.io/page/fast-fibonacci-algorithms, with a base case that uses math.pow.

Code
Diff
  • from math import sqrt
    
    def fib(x):
        if x < 70:
            a = 0.7236067977499789 # (sqrt(5) + 1) / (2 * sqrt(5))
            b = 1.618033988749895 # (1 + sqrt(5)) / 2
            return round(a * b**x)
        elif x % 2 == 0:
            a = fib(x / 2)
            b = fib(x / 2 + 1)
            return a * (2 * fib(b) - a)
        else:
            # x % 2 == 1, by elimination
            a = fib((x - 1) / 2)
            b = fib((x + 1) / 2)
            return a * a + b * b
    
    • # Fibonacci #
    • from math import sqrt
    • c1 = (sqrt(5) - 1) / (2 * sqrt(5))
    • c2 = (sqrt(5) + 1) / (2 * sqrt(5))
    • def f(x):
    • fibo = c1 * ((1 - sqrt(5)) / 2)**x + c2 * ((1 + sqrt(5)) / 2)**x
    • return int(round(fibo))
    • def fib(x):
    • if x < 70:
    • a = 0.7236067977499789 # (sqrt(5) + 1) / (2 * sqrt(5))
    • b = 1.618033988749895 # (1 + sqrt(5)) / 2
    • return round(a * b**x)
    • elif x % 2 == 0:
    • a = fib(x / 2)
    • b = fib(x / 2 + 1)
    • return a * (2 * fib(b) - a)
    • else:
    • # x % 2 == 1, by elimination
    • a = fib((x - 1) / 2)
    • b = fib((x + 1) / 2)
    • return a * a + b * b