C—A/B
原题链接:https://vjudge.net/problem/HDU-1576/origin
题目大意:
题目分析:
模运算中,有
加的:(a+b)%c == a%c + b%c
减的:(a-b)%c == a%c - b%c
乘的:(a*b)%c == a%c * b%c
就是 没有 除的:(a/b)%c == (a%c)/(b%c) … …(错误!错误!错误!)
但定义了逆元:当a*b ≡ 1(mod p),那么b就称为a的逆元,a称为b的逆元
求逆元
如果要求b在模质数c下的逆元,则
假设b的逆元为inv(b),则由定义得:b*inv(b) ≡ 1(mod c)
再由 费马小定理 :当p为质数,a不是p的倍数时,有ap-1 ≡ 1(mod p)
可得:b*inv(b) == bc-1,则inv(b) == bc-2,结合快速幂可以算出
回到题目,由于B*inv(B) ≡ 1(mod 9973),可得inv(B) == B9973-2
则 A/B ≡ A/B * (B*inv(B)) ≡ A * inv(B) ≡ A*B9973-2 (mod 9973) == (A mod 9973) * (B9973-2 mod 9973) == n * (B9973-2 mod 9973)
代码实现:
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef long long LL;
LL pow_quick(LL a, LL b, LL m) //快速幂
{
LL ans = 1;
while(b)
{
if(b&1) ans = ans*a%m;
a = a*a%m;
b >>= 1;
}
return ans;
}
int main()
{
int t;
const LL C = 9973;
LL n, b;
cin >> t;
while(t--)
{
cin >> n >> b;
cout << n*pow_quick(b,C-2,C)%C << endl;
}
return 0;
}