数论
快速幂求逆元
给定 n 组 ai,pi,其中 pi 是质数,求 ai 模 pi 的乘法逆元,若逆元不存在则输出 impossible
。
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
// a^k mod p
int 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()
{
int n;
scanf("%d",&n);
while(n--)
{
int a,p;
scanf("%d%d",&a,&p);
if(a % p == 0){
printf("impossible");
puts("");
continue;
}
printf("%d\n",qmi(a, p - 2, p));
}
return 0;
}
裴蜀定理
若a,b是整数,且gcd(a,b)=d,那么对于任意的整数x,y,ax+by都一定是d的倍数,特别地,一定存在整数x,y,使ax+by=d成立。
扩展欧几里得算法
给定 n 对正整数 ai,bi,对于每对数,求出一组 xi,yi,使其满足 ai×xi+bi×yi=gcd(ai,bi)。
#include<iostream>
using namespace std;
int exgcd(int a,int b,int &x,int &y){
if(!b){
x = 1,y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
x = x;
y -= a / b * x;
return d;
}
int main(){
int n;
scanf("%d",&n);
while(n--){
int a,b,x,y;
scanf("%d%d",&a,&b);
exgcd(a,b,x,y);
printf("%d %d\n",x,y);
}
return 0;
}