给定 n 组 ,
,其中
是质数,求
mod
的乘法逆元,若逆元不存在则输出
impossible
。
注意:请返回在 0∼p−1 之间的逆元。
乘法逆元的定义
若整数 b,m 互质,并且对于任意的整数 a,如果满足 b|a,则存在一个整数 x,使得
,则称 x 为 b 的模 m 乘法逆元,记为
。
b 存在乘法逆元的充要条件是 b 与模数 m 互质。当模数 m 为质数时,
即为 b 的乘法逆元。
输入格式
第一行包含整数 n。
接下来 n 行,每行包含一个数组 ,
,数据保证
是质数。
输出格式
输出共 n 行,每组数据输出一个结果,每个结果占一行。
若 mod
的乘法逆元存在,则输出一个整数,表示逆元,否则输出
impossible
。
数据范围
1≤n≤,
1≤,
≤2∗
输入样例:
3
4 3
8 5
6 3
输出样例:
1
2
impossible
代码:
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n,p;
long long a,b;
long long QuickMul(long long a,long long b,int p){
long long res = 1;
while(b != 0){
if(b & 1 == 1){
res = res * a % p;
}
b = b / 2;
a = a * a % p;
}
return res;
}
int main(){
cin>>n;
while(n--){
cin>>a>>p;
long long ans = QuickMul(a,p-2,p);
if(a % p == 0){
cout<<"impossible"<<endl;
}else{
cout<<ans<<endl;
}
}
return 0;
}