hdu 1576 AB 乘法逆元 费马小定理

it2023-04-17  74

现学现卖

1.乘法逆元用来解决 (a/b)%p的问题 因为(a/b)%p 不等于 (a%p)/(b*p)

2.引入逆元相当于 把除法问题转化为乘法问题

3.当然要满足 ==1的条件 (类比于矩阵的逆)

4.本题进行转化后发现 gcd(B,9973)=1 直接上 快速幂(费马小定理)

#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #define LL long long using namespace std; const LL p=9973; LL get_inv(LL x,LL mp){ LL bse(x%p),ans(1); while (mp){ if (mp&1) ans=ans*bse%p; bse=bse*bse%p; mp>>=1; } return ans%p; } int T; LL n,B; int main (){ scanf ("%d",&T); while (T--){ scanf ("%lld%lld",&n,&B); if (!n) puts ("0"); else printf ("%lld\n",n*get_inv(B,p-2)%p); } return 0; }

细节问题:

1.快速幂 写错 D了好久 

    ans*=ans%p  ×   因为%运算与*同级   所以大一点数据的时候直接溢出

最新回复(0)