Skip to content

Commit

Permalink
Merge pull request #160 from 2knal/master
Browse files Browse the repository at this point in the history
  • Loading branch information
dnery authored Oct 19, 2019
2 parents c678160 + 70e4331 commit a60ff91
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions math/fibonacci/python/fastDoublingNthFibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'''
Fast Doubling method: https://www.hackerearth.com/practice/notes/fast-doubling-method-to-find-nth-fibonacci-number/
Fibonacci series: 0 1 1 2 3 ...
NthFibonacci(n, mod) -> int
mod: We find modulo of number (usually with 1e9+7), as it is too big.
'''

def NthFibonacci(n, mod):
return int(NthFibonacciHelper(n, mod)[0])

def NthFibonacciHelper(n, mod):
if not n:
return (0, 1)
else:
a, b = NthFibonacciHelper(n // 2, mod)
c = (a%mod * ((b*2)%mod - a%mod))%mod
d = ((a%mod * a%mod)%mod + (b%mod * b%mod)%mod)%mod

if not n&1:
return (c, d)
else:
return (d, c + d)

0 comments on commit a60ff91

Please sign in to comment.