A/B
题目链接:HDU - 1576中文题, 直接附上题目内容:
要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1)。
设x=(A/B)%9973->9973*k+x=A/B->A=9973*k*B+x*B
n=A%9973->n=(9973*k*B+x*B)%9973->n=x*B%9973->n+9973y=x*B->x*B-9973y=n->x/n*B-y/n*9973=1=gcd(B, 9973)=>x*B-n=9973*y=>(x*B-n)%9973=0;
根据公式可得出结论,该题既可用扩展欧几里得计算, 也可以暴力求解;
如果想深入了解扩展欧几里得算法请戳这里
代码附上:
扩展欧几里得解法:
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
long long exgcd(long long a, long long b, long long &x, long long &y){
if(b==0){
x=1, y=0;
return a;
}
long long r=exgcd(b, a%b, x, y);
long long t=x;
x=y;
y=t-a/b*y;
return r;
}
int main(){
int T;
cin >> T;
while(T--){
long long n, B;
cin >> n >> B;
long long x, y;
long long r=exgcd(B, 9973, x, y);
x=(x%9973+9973)*n%9973;
cout << x << endl;
}
return 0;
}
暴力解法:
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main(){
int T;
cin >> T;
while(T--){
long long n, B;
cin >> n >> B;
for(int i=0; i<=9973; i++){
if((i*B-n)%9973==0){
cout << i << endl;
break;
}
}
}
return 0;
}