HDU-1576(A/B)拓展欧几里得

来源:互联网 发布:下载天盾数据恢复软件 编辑:程序博客网 时间:2024/06/05 20:04

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

从题目中我们可以推出A = y*9973 + n,而且A可以被B整除故,A=x*B,故我们可以知道y*9973+n = x*B,即B*x-9973*y = n,显然这是一个 拓展欧几里得的算法,我们可以求出B*x-9973*y=1中的x0,y0,两边同时乘上一个n就是上一个方程的答案,由于A/B=x,故ans = x%9973;
完整代码如下:

#include<iostream>#include<algorithm>using namespace std;typedef long long ll;ll extgcd(ll a,ll b,ll &x,ll &y){    ll d = a;    if(b != 0){        d = extgcd(b,a%b,y,x);        y -= (a/b)*x;    }else{        x = 1;        y = 0;    }    return d;}int main(void){    ll t,n,b;    cin >> t;    while(t--){        cin >> n >> b;        ll x,y;        extgcd(b,9973,x,y);//这里y求出来的只是A=9973*y+n中的y         while(x <= 0)//当x小于0时,让其变为x>0的解。         x += 9973;        cout << n*x%9973 << endl;    }    return 0;}
0 0
原创粉丝点击