A/B(扩展欧几里德)

A/B

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3340    Accepted Submission(s): 2534


Problem Description
要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1)。
 
Input
数据的第一行是一个T,表示有T组数据。
每组数据有两个数n(0 <= n < 9973)和B(1 <= B <= 10^9)。
 
Output
对应每组数据输出(A/B)%9973。
 
Sample Input
2 1000 53 87 123456789
 
Sample Output
7922 6060
 
Author
xhd
题解:我列的等式是B*x-9973*y=n;
带入-9973竟然不对。。。还想着x%9973还可能为负数呐,看来自己连取模定义都不知道。。。。x%9973=(x+9973)%9973;x不能为负。。。。话不多说,代码贴上;
代码:
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<vector>
 7 #define mem(x,y) memset(x,y,sizeof(x))
 8 using namespace std;
 9 typedef long long LL;
10 const int INF=0x3f3f3f3f;
11 LL e_gcd(LL a,LL b,LL &x,LL &y){
12     if(!b){
13         x=1;y=0;
14         return a;
15     }
16     else{
17         LL d=e_gcd(b,a%b,x,y);
18         LL temp=x;
19         x=y;
20         y=temp-a/b*y;
21         return d;
22     }
23 }
24 LL cal(LL a,LL b,LL c){
25     LL x,y,gcd;
26     gcd=e_gcd(a,b,x,y);
27     x*=(c/gcd); 
28     if(b<0)b=-b;
29     b/=gcd;
30     x=x%b;
31     if(x<=0)x+=b;
32     return x%9973;
33 }
34 int main(){
35     LL T,n,b;
36     scanf("%lld",&T);
37     while(T--){
38         scanf("%lld%lld",&n,&b);
39         printf("%lld
",cal(b,9973,n));
40     }
41     return 0;
42 }
原文地址:https://www.cnblogs.com/handsomecui/p/4908602.html