-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1013.py
More file actions
31 lines (31 loc) · 940 Bytes
/
1013.py
File metadata and controls
31 lines (31 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def mul(a,b,mod): #Multiplication of two matrices (matrices A and B have the same size)
n = len(a)
result = []
for i in range(n):
result.append([0]*n)
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] = (result[i][j] + a[i][k]*b[k][j]%mod)%mod
return result
def binpow(a,n,mod): #Binary exponentiation of a matrix, this is possible because the matrix multiplication operation is associative
if n==2:
return mul(a,a,mod)
if(n%2==1):
return mul(binpow(a,n-1,mod),a,mod)
x = binpow(a,n//2,mod)
return mul(x,x,mod)
def check(n,k,mod):
if n==2:
return (k-1)*k%mod
if n==1:
return k-1
return -1
n = int(input())
k = int(input())
mod = int(input())
if check(n,k,mod) != -1:
print(check(n,k,mod))
quit()
x = binpow([[0,k-1],[1,k-1]],n-2,mod)
print(((k-1)*x[0][1]%mod + (k-1)*k%mod*x[1][1])%mod)