快速幂
O(logk)
ll qmi(ll m, ll k, ll p)//求m^k%p,p>1e9用龟速乘
{
ll res = 1;
while (k)
{
if (k & 1)
{
res = res * m % p;
}
m = m * m % p;
k >>= 1;
}
return res;
}
快速幂求逆元
O(logp)
ll a, p;//求a%p的乘法逆元,p为质数
cin >> a >> p;
if(a%p)
{
cout << qmi(a, p-2, p) << endl;
}
else
{
cout<<"impossible"<<endl;
}
矩阵快速幂
O(logn)
int n, m;//n为次数,m为模数
void mul(int c[], int a[], int b[][N])
{
int temp[N] = {0};
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
temp[i] = (temp[i] + (ll)a[j] * b[j][i]) % m;
}
}
memcpy(c, temp, sizeof temp);
}
void mul(int c[][N], int a[][N], int b[][N])
{
int temp[N][N] = {0};
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
for (int k = 0; k < N; k++)
{
temp[i][j] = (temp[i][j] + (ll)a[i][k] * b[k][j]) % m;
}
}
}
memcpy(c, temp, sizeof temp);
}
int main()
{
std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0);
cin >> n >> m;
int res[N] = {1, 1, 1}; //初始化
int a[N][N] = { //初始化
{0, 1, 0},
{1, 1, 1},
{0, 0, 1}
};
n--;
while (n)
{
if (n & 1)
{
mul(res, res, a);
}
mul(a, a, a);
n >>= 1;
}
cout << res[2] << endl;//输出对应结果
return 0;
}
龟速乘
ll qmul(ll a, ll b, ll p)
{
ll sum = 0;
while (b)
{
if (b & 1)
{
sum = (sum + a) % p;
}
a = (a + a) % p;
b >>= 1;
}
return sum;
}
ll qmi(ll m, ll k, ll p) //求m^k%p
{
ll res = 1;
while (k)
{
if (k & 1)
{
res = qmul(res, m, p);
}
m = qmul(m, m, p);
k >>= 1;
}
return res;
}