Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create fastDoublingNthFibonacci.py #160

Merged
merged 1 commit into from
Oct 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very interesting!

I didn't know about that programming pattern...

Thanks for sharing! 😄

'''

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:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

( ͡° ͜ʖ ͡°)

return (c, d)
else:
return (d, c + d)