算法程序员

快速幂求逆元

2019-10-14  本文已影响0人  _NewMoon

逆元的定义

若整数b,m互质,并且b|a,则存在一个整数x,使得a/b≡a∗x(mod m),则称x为b的模m乘法逆元,记为b−1(mod m)。

b存在乘法逆元的充要条件是b与模数m互质。否则,b不存在乘法逆元。当模数m为质数时,b^(m−2)即为b的乘法逆元。

如何求逆元

题目示例:Acwing876.快速幂求逆元https://www.acwing.com/problem/content/878/

代码:

//求逆元模板
#include <iostream>
#include <algorithm>
#include <cstdio>

using namespace std;

typedef long long LL;

int n,p;

//快速幂取余模板
LL qmi(int a,int k,int p)
{
    LL res = 1;
    while(k)
    {
        if(k&1) res = (LL)res*a%p;
        a = a*(LL)a%p;
        k>>=1;
    }
    return res;
}
int main()
{
    cin>>n;
    
    while(n--)
    {
        int a,p;
        scanf("%d%d",&a,&p);
        if(a%p)      
            printf("%d\n",qmi(a,p-2,p));
        else      //由费马小定理可知,如果a是p的倍数,则不存在
            puts("impossible");
    }
    
    return 0;
}

长风破浪会有时,直挂云帆济沧海

上一篇 下一篇

猜你喜欢

热点阅读