HDU A/B 扩展欧几里得

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
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
/*
要求(A/B)%9973
ax+by = c
a*x = c%b 在这里b=9973,
9973*x+B*y = A
B*y = A%9973 在这里求最小的B就是答案
按照求逆元的方法
*/ LL ex_gcd(LL a,LL b,LL &x,LL &y) { if(b==0) { x = 1; y = 0; return a; } LL ans = ex_gcd(b,a%b,x,y); LL tmp = x; x = y; y = tmp - a/b*x; return ans; } LL cal(LL a,LL b,LL c) { LL x=0,y=0; LL gcd = ex_gcd(a,b,x,y); if(c%gcd!=0) return -1; x *= c/gcd; b /= gcd; if(b<0) b = -b; LL ans = x%b; if(ans<0) ans += b; return ans; } int main() { LL t,n,b; scanf("%lld",&t); while(t--) { scanf("%lld%lld",&n,&b); printf("%lld ",cal(b,9973,n)); } }
原文地址:https://www.cnblogs.com/joeylee97/p/6658201.html