hdu 1576 求逆元

时间:2021-10-28 07:25:21

题意:给出n=A mod 9973和B,求(A/B) mod 9973

昨天用扩展欧几里得做过这题,其实用逆元也可以做。

逆元的定义:例如a*b≡1 (mod m),则b就是a关于m的逆元。

求逆元方法也很简单,用扩展欧几里得解这个方程即可。

逆元性质:若a是b的逆元,则(x/a)mod p=(x*b)mod p

对于本题呢?设B的逆元为x,

那么有(A/B) mod 9973=((A mod 9973)*(x mod 9973))mod 9973

Reference:  http://blog.csdn.net/leonharetd/article/details/13095191

 #include <iostream>
using namespace std;
__int64 a,b,b1,x,k,tm,r,T,n,ans; __int64 extend_gcd(__int64 a,__int64 b,__int64 &x,__int64 &y)
{
if (b==)
{
x=;
y=;
return a;
}
else
{
__int64 r=extend_gcd(b,a%b,y,x);
y=y-x*(a/b);
return r;
}
} int gcd(int a,int b)
{
if (b==) return a;
return gcd(b,a%b);
} int main()
{
cin>>T;
while (T--)
{
cin>>n>>b;
//bx==1 (mod m)
tm=extend_gcd(b,,x,k);
b1=x*(/tm);
r=/tm;
b1=(b1%r+r)%r; //求出最小非负整数解
ans=(n*(b1%))%;
cout<<ans<<endl; }
return ;
}