[AcWing 876] 快速幂求逆元

image
image

复杂度 $ O(log(k)) $ (k 是指数)

总体复杂度 $ 10^{5} \times log(2 \times 10^{9}) \approx 4 \times 10^{6} $


点击查看代码
#include<iostream>

using namespace std;
typedef long long LL;

LL qmi(int a, int k, int p)
{
    LL res = 1;
    while (k) {
        if (k & 1)  res = 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)  puts("impossible");
        else    printf("%lld\n", qmi(a, p - 2, p));
    }
    return 0;
}

  1. 乘法逆元
    image
    用 $ x $ 表示 $ b $ 的逆元,证明如下:在 $ \bmod m $ 的情况下, $ \frac{a}{b} \equiv a \times x \rightarrow b \times \frac{a}{b} \equiv a \times b \times x \rightarrow a \equiv a \times b \times x \rightarrow b \times x \equiv 1 $
    由费马小定理:如果 $ p $ 是一个质数,而整数 $ a $ 不是 $ p $ 的倍数,则有 $ a^{p - 1} \equiv 1 \ (\ \bmod p) $
    可得 $ b^{p-1} = b \times b^{p-2} \equiv 1 $ ,在上面已经推出 $ b \times x \equiv 1 $ ,故 $ b^{p-2} $ 即为 $ b $ 的逆元 $ x $
  2. 快速幂模板
    在 $ a \bmod p = 0 $ 时输出 "impossible";
    否则就用快速幂求 $ a^{p-2} \bmod p $ 的值;
posted @ 2022-05-09 21:38  wKingYu  阅读(44)  评论(0)    收藏  举报