快速幂求逆元

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>
using namespace std;

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

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

int main(){
    int n;
    cin>>n;
    while(n--)
    {
        int a,b;
        cin>>a>>b;
        if(gcd(a,b)!=1)
        {
            cout<<"impossible"<<endl;
        }
        else cout<<qmi(a,b-2,b)<<endl;
    }
    return 0;
}

发布了152 篇原创文章 · 获赞 4 · 访问量 3900

猜你喜欢

转载自blog.csdn.net/qq_43716912/article/details/100066565
今日推荐