题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1576
题目:要求(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
题目分析:
1.已知n,B的值,要求(A/B)%9973的结果。其中n=A%9973,gcd(B,9973)=1;
假设 ans 是(A / B)%9973的结果,即(A / B)%9973=ans
可知存在一个x使得 9973*x+ans=(A / B)
所以:A=9973*Bx+ans*B..........(1)
又因为 n=A%9973,所以存在一个y ,使得A=9973*y+n.............(2)
由(1)(2)式得9973*y+n=9973*Bx+ans*B
转换后得:n=9973Bx+ans*B-9973y=9973(Bx-y)+ans*B====>(两边同时除以n后得到)(ans/n)*B+(Bx-y)/n*9973=1........(3)
由已知gcd(B,9973)=1......(4)
由(3)(4)条件得知,可以将式子看成是ax+by=1的形式
运用扩展欧几里得算法能够求出 ans/n 的值(假设为res),最终的结果为 res*n;
代码实现:
#include<cstdio>
#include<iostream>
using namespace std;
void exgcd(int a,int b,int &x,int &y)
{
if(b==)
{
x=;
y=;
return ;
}
exgcd(b,a%b,x,y);
int t=x;
x=y;
y=t-a/b*y;
}
int main()
{
int T,n,b,x,y;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&b);
exgcd(b,,x,y);
x=x*n;
x=(x%+)%;//防止x为负数
printf("%d\n",x);
}
return ;
}