21000 5387 123456789Sample Output79226060对于任意整数a,b,总有ax+by=gcd(a,b).x,y为整数,
若整数a,b互质,则有ax+by=gcd(a,b)=1,x,y为整数,则k*a%b=1.其中k为整数。
称x为a关于mod b的逆元。
此题中,要求a/b%n,因为除法中不能模,所以转换,则:
a / b % n = a / b * 1 % n = a / b * b(逆) * b % n = a * b(逆) % n.
即使用欧几里得算法求出B与模数9973的逆元与A相乘即可。
欧几里得算法证明:
a * x + b * y = gcd (a , b) = gcd (b , a % b) = b * x1 + (a % b) * y1
素数时:a * x % b = 1
a * x + b * y = b * x1 + (a % b) * y1
= b * x2 + (a - (int)(a / b) * b ) * y1
= b * x1 + a * y1 - (int)(a / b) * y1 * b
因为此为等式,所以两边a,b对应系数相等
整理:
x = y1;
y = x1 - (int)(a / b) * y1;
当通过辗转相除法进行到最底层,即b == 0时:
得到 xk = ak , yk = 0;
返回上层得到对应的 x(k - 1) = yk = 0 , y(k - 1) = xk - (int)( a(k - 1) / b(k - 1)) * yk = ak ;
实现:
void gcd(LL A, LL B, LL &d, LL &x, LL &y){//欧几里得算法实现 if(!B){d=A,x=1,y=0;} else { gcd(B,A%B,d,y,x); y-=x*(A/B); } return ;}Code:(0ms)#include<iostream>#include<cstdio>#include<cmath>using namespace std;typedef long long LL;const LL mod=9973;void gcd(LL A, LL B, LL &d, LL &x, LL &y){ if(!B){d=A,x=1,y=0;} else { gcd(B,A%B,d,y,x); y-=x*(A/B); } return ;}int main(){ int T,A,B; LL d,x,y; scanf("%d", &T); while(T){ --T; scanf("%d%d", &A,&B); gcd(B,mod,d,x,y); A=A*x%mod; if(A<0)A+=mod; PRintf("%d/n",A); } return 0;}
新闻热点
疑难解答