给定 n 组 ai,pi,其中 pi 是质数,求 ai 模 pi 的乘法逆元,若逆元不存在则输出 impossible。
注意:请返回在 0∼p−1 之间的逆元。
若整数 b,m 互质,并且对于任意的整数 a,如果满足 b|a,则存在一个整数 x,使得 a/b≡a×x(modm),则称 x 为 b 的模 m 乘法逆元,记为 b−1(modm)。
b 存在乘法逆元的充要条件是 b 与模数 m 互质。当模数 m 为质数时,bm−2 即为 b 的乘法逆元。
第一行包含整数 n。
接下来 n 行,每行包含一个数组 ai,pi,数据保证 pi 是质数。
输出共 n 行,每组数据输出一个结果,每个结果占一行。
若 ai 模 pi 的乘法逆元存在,则输出一个整数,表示逆元,否则输出 impossible。
1≤n≤105,
1≤ai,pi≤2∗109
- 3
- 4 3
- 8 5
- 6 3
- 1
- 2
- impossible
若整数 b,m 互质,并且对于任意的整数 a,如果满足 b|a(a能整除b),则存在一个整数 x,使得 a/b≡a×x(modm),则称 x 为 b 的模 m 乘法逆元,记为 b−1(modm)。
b 存在乘法逆元的充要条件是 b 与模数 m 互质。当模数 m 为质数时,bm−2 即为 b 的乘法逆元。
更通俗的讲:
给你一个数 b ,找出一个 x ,使得 b*x≡1(mod m)b与m互质
根据定义:
a/b≡a*x(mod m)
我设 b 的逆元为 b^-1
则 a/b≡a*b^-1(mod m)
b*a/b≡a*b^-1*b(mod m)
a≡a*b^-1*b (mod m)
可表示为:b*b^-1≡1 (mod m)
所以逆元类似于乘法中的倒数
费马小定理:
b^(p-1)≡1 (mod p)
则 b*b^(p-2)≡1 (mod p)
所以求一个数 b mod p 的逆元,只需要求出 b^(p-2) 即可
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- using namespace std;
- typedef long long LL;
- int a, p;
-
- LL quickpow(LL x, LL y, LL mod) {
- LL t = a, ret = 1;
- while (y) {
- if (y & 1)ret = (ret * t) % mod;
- y >>= 1;
- t = (t * t) % mod;
- }
- return ret;
- }
-
- int main() {
- int n;
- scanf("%d", &n);
- while (n--) {
- scanf("%d%d", &a, &p);
- LL ret = quickpow(a,p-2,p);
- if (a % p)
- printf("%lld\n", ret);
- else
- printf("impossible\n");
- }
- return 0;
- }