-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
maths: add O(log n) Fibonacci via matrix exponentiation #14557
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
Open
AKIB473
wants to merge
4
commits into
TheAlgorithms:master
Choose a base branch
from
AKIB473:akib/fibonacci-fast
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+103
−0
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
53a30c4
maths: add O(log n) Fibonacci via matrix exponentiation
66919bd
style: fix ruff linting — replace ambiguous multiplication sign, appl…
4280d0e
fix: use descriptive parameter names (mat_a, mat_b, index) per review
AKIB473 382ee44
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| """ | ||
| Fibonacci sequence via matrix exponentiation — O(log n) time complexity. | ||
|
|
||
| The standard recursive Fibonacci runs in O(2^n) time. Using matrix exponentiation | ||
| we can compute the n-th Fibonacci number in O(log n) multiplications. | ||
|
|
||
| The key identity is: | ||
| | F(n+1) F(n) | | 1 1 | ^ n | ||
| | F(n) F(n-1) | = | 1 0 | | ||
|
|
||
| So F(n) = (M^n)[0][1] where M = [[1, 1], [1, 0]]. | ||
|
|
||
| References: | ||
| - https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form | ||
| """ | ||
|
|
||
|
|
||
| def _mat_mul( | ||
| a: list[list[int]], b: list[list[int]] | ||
| ) -> list[list[int]]: | ||
| """Multiply two 2×2 integer matrices. | ||
|
|
||
| >>> _mat_mul([[1, 1], [1, 0]], [[1, 0], [0, 1]]) | ||
| [[1, 1], [1, 0]] | ||
| """ | ||
| return [ | ||
| [ | ||
| a[0][0] * b[0][0] + a[0][1] * b[1][0], | ||
| a[0][0] * b[0][1] + a[0][1] * b[1][1], | ||
| ], | ||
| [ | ||
| a[1][0] * b[0][0] + a[1][1] * b[1][0], | ||
| a[1][0] * b[0][1] + a[1][1] * b[1][1], | ||
| ], | ||
| ] | ||
|
|
||
|
|
||
| def _mat_pow(matrix: list[list[int]], power: int) -> list[list[int]]: | ||
| """Raise a 2×2 integer matrix to a non-negative integer power using | ||
| fast exponentiation (repeated squaring). | ||
|
|
||
| :param matrix: A 2×2 matrix represented as a list of lists. | ||
| :param power: Non-negative integer exponent. | ||
| :return: matrix ** power | ||
|
|
||
| >>> _mat_pow([[1, 1], [1, 0]], 0) | ||
| [[1, 0], [0, 1]] | ||
| >>> _mat_pow([[1, 1], [1, 0]], 1) | ||
| [[1, 1], [1, 0]] | ||
| >>> _mat_pow([[1, 1], [1, 0]], 2) | ||
| [[2, 1], [1, 1]] | ||
| """ | ||
| # Identity matrix | ||
| result: list[list[int]] = [[1, 0], [0, 1]] | ||
| while power: | ||
| if power % 2 == 1: | ||
| result = _mat_mul(result, matrix) | ||
| matrix = _mat_mul(matrix, matrix) | ||
| power //= 2 | ||
| return result | ||
|
|
||
|
|
||
| def fibonacci(n: int) -> int: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please provide descriptive name for the parameter: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please provide descriptive name for the parameter: |
||
| """Return the n-th Fibonacci number using matrix exponentiation. | ||
|
|
||
| Time complexity: O(log n) | ||
| Space complexity: O(log n) due to the call stack of _mat_pow | ||
|
|
||
| :param n: Non-negative integer index into the Fibonacci sequence | ||
| (0-indexed: F(0)=0, F(1)=1, F(2)=1, ...). | ||
| :raises ValueError: If *n* is negative. | ||
| :return: The n-th Fibonacci number. | ||
|
|
||
| >>> fibonacci(0) | ||
| 0 | ||
| >>> fibonacci(1) | ||
| 1 | ||
| >>> fibonacci(2) | ||
| 1 | ||
| >>> fibonacci(10) | ||
| 55 | ||
| >>> fibonacci(20) | ||
| 6765 | ||
| >>> fibonacci(50) | ||
| 12586269025 | ||
| >>> fibonacci(-1) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: fibonacci() only accepts non-negative integers | ||
| """ | ||
| if n < 0: | ||
| raise ValueError("fibonacci() only accepts non-negative integers") | ||
| if n == 0: | ||
| return 0 | ||
| m: list[list[int]] = [[1, 1], [1, 0]] | ||
| return _mat_pow(m, n)[0][1] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import doctest | ||
|
|
||
| doctest.testmod() | ||
|
|
||
| for i in range(15): | ||
| print(f"fibonacci({i}) = {fibonacci(i)}") | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please provide descriptive name for the parameter:
aPlease provide descriptive name for the parameter:
b