Skip to content

Commit 2e4effb

Browse files
Merge pull request #2875 from 19WH1A0524/master
Updated Matrix_Expo.mdx with python code
2 parents 3f7aa44 + 997df32 commit 2e4effb

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

content/5_Plat/Matrix_Expo.mdx

+44-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,11 @@ $$
8383
The base case is true, and the induction step is true. Therefore the formula
8484
holds for all $n \in \mathbb{N}$.
8585

86-
### Implementation
86+
<LanguageSection>
87+
88+
<CPPSection>
89+
90+
## Implementation
8791

8892
**Time complexity:** $\mathcal{O}(\log n)$
8993

@@ -124,7 +128,46 @@ int main() {
124128
cout << base[0][1];
125129
}
126130
```
131+
</CPPSection>
132+
133+
<PySection>
134+
```python
135+
from typing import List
136+
137+
MOD = 10 ** 9 + 7
138+
139+
def mul(A : List[List[int]], B : List[List[int]], MOD : int) -> List[List[int]]:
140+
C = [[0, 0], [0, 0]]
141+
for i in range(2):
142+
for j in range(2):
143+
for k in range(2):
144+
C[i][j] += ((A[i][k]) * (B[k][j])) % MOD
145+
return C
146+
147+
def power(matrix : List[List[int]], n : int) -> List[List[int]]:
148+
if n == 0:
149+
return [[1, 0], [0, 1]]
150+
if n == 1:
151+
return matrix
152+
half = power(matrix, n // 2, MOD)
153+
square = mul(half, half, MOD)
154+
if n % 2 == 0:
155+
return square
156+
return mul(matrix, square, MOD)
157+
158+
159+
n = int(input())
160+
if n == 0:
161+
print(0)
162+
elif n > 2:
163+
o = power([[1, 1], [1, 0]], n - 1)
164+
print(o[0][0] % MOD)
165+
else:
166+
print(1)
127167
168+
```
169+
</PySection>
170+
</LanguageSection>
128171
## Problems
129172

130173
<Problems problems="probs" />

0 commit comments

Comments
 (0)