快速幂模板
求a的k次方模p的结果
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL qmi(int a, int k, int p)
{
int res = 1;
while(k)
{
if(k & 1)
res = (LL) res * a % p;
k >>= 1;
a = (LL) a * a % p;
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
while(n--)
{
int a, k, p;
cin >> a >> k >> p;
cout << qmi(a, k, p) << endl;
}
return 0;
}
快速幂求逆元
当n为质数时,可以用快速幂求逆元:
a / b ≡ a * x (mod n)
两边同乘b可得 a ≡ a * b * x (mod n)
即 1 ≡ b * x (mod n)
同 b * x ≡ 1 (mod n)
由费马小定理可知,当n为质数时
b ^ (n - 1) ≡ 1 (mod n)
拆一个b出来可得 b * b ^ (n - 2) ≡ 1 (mod n)
故当n为质数时,b的乘法逆元 x = b ^ (n - 2)
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL qmi(int a, int k, int p)
{
int res = 1;
while(k)
{
if(k & 1)
res = (LL) res * a % p;
k >>= 1;
a = (LL) a * a % p;
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
while(n--)
{
int a, k, p;
cin >> a >> p;
//费马小定理:
//如果p是一个质数,而整数a不是p的倍数,则有a^(p-1)≡1(mod p)。
if(a % p == 0)
puts("impossible");
else
printf("%d\n", qmi(a, p - 2, p));
}
return 0;
}