Skip to content

Commit 2213347

Browse files
committed
A fast recursive implementation of fibonacci numbers
1 parent 9629aef commit 2213347

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

fast_recursive_fibonacci.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def fast_rec_fib_helper(n):
2+
"""returns the last two elements of the fibonacci sequence."""
3+
if n == 1:
4+
return (0,1)
5+
m = n//2
6+
hprv, hcur = fast_rec_fib_helper(m)
7+
prev = (hprv ** 2) + (hcur **2)
8+
curr = hcur * (2 * hprv + hcur)
9+
next = prev + curr
10+
if n % 2 == 0:
11+
return (prev, curr)
12+
else:
13+
return (curr, next)
14+
15+
def fast_rec_fib(n):
16+
previous, current = fast_rec_fib_helper(n)
17+
return current
18+
19+
print(fast_rec_fib(1000))

0 commit comments

Comments
 (0)