Skip to content

Commit b9d78fd

Browse files
authored
Merge pull request #2 from AranMesquita/fibonacci-code
added fibonacci matrix exponentiation implementation in python and rust
2 parents bc7c373 + 808c3ea commit b9d78fd

File tree

3 files changed

+41
-7
lines changed

3 files changed

+41
-7
lines changed

src-py/example.py

Lines changed: 0 additions & 7 deletions
This file was deleted.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def _power(m: list[int], n: int) -> list[int]:
2+
result = [1, 0, 0, 1]
3+
while n > 0:
4+
if n % 2 == 1:
5+
result = _multiply(result, m)
6+
7+
m = _multiply(m, m)
8+
n //= 2
9+
10+
return result
11+
12+
13+
def _multiply(a: list[int], b: list[int]) -> list[int]:
14+
return [
15+
a[0] * b[0] + a[1] * b[2],
16+
a[0] * b[1] + a[1] * b[3],
17+
a[2] * b[0] + a[3] * b[2],
18+
a[2] * b[1] + a[3] * b[3],
19+
]
20+
21+
22+
def python_nth_fibonacci_using_matrix_exponentiation(n: int) -> int:
23+
if n == 0:
24+
return 0
25+
else:
26+
base = [1, 1, 1, 0]
27+
result = _power(base, n - 1)
28+
return result[0]

src-py/main.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import test_rust_in_python
2+
from fibonacci_matrix_exponentiation import python_nth_fibonacci_using_matrix_exponentiation
3+
4+
5+
RUST_FUNCTIONS = test_rust_in_python
6+
7+
rust_fibonacci_reuslt = RUST_FUNCTIONS.rust_nth_fibonacci_using_matrix_exponentiation(93) # type: ignore
8+
9+
print(f"Result from Rust: {rust_fibonacci_reuslt}")
10+
11+
12+
python_fibonacci_reuslt = python_nth_fibonacci_using_matrix_exponentiation(93)
13+
print(f"Result from Python: {python_fibonacci_reuslt}")

0 commit comments

Comments
 (0)