求逆元 判断是否有逆元

#include <stdio.h>

using namespace std;
typedef long long ll;
int a,p,m;

int gcd(int a,int b){
    if(!b){
        return a;
    }
    return gcd(b,a%b);
}

int quick_pow(int a,int b,int p){
    int res=1;
    while(b){
        if(b&1)res=(ll)res*a%p;
        a=(ll)a*a%p;
        b>>=1;
    }
    return res;
}

int inv(int a,int p){
    return quick_pow(a,p-2,p);
}
int main()
{
    scanf("%d",&m);
    while(m--){
        scanf("%d%d",&a,&p);
        if(gcd(a,p)==1)printf("%d\n",inv(a,p));
        else puts("impossible");
    }
    return 0;
}

 posted on 2019-08-16 17:31  谁是凶手1703  阅读(36)  评论(0)    收藏  举报