sincerit 1576 A/B 擴充套件歐幾里得
1576 A/B
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9629 Accepted Submission(s): 7732
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
分析(從大佬那抄過來的以後可以看看):https://blog.csdn.net/zwj1452267376/article/details/50151161
n=A%9973,則n=A-A/99739973。又A/B=x,則A=Bx。所以Bx-A/99739973=n。即Bx-9973y=n。
在這裡我們知道只要求出x的值就能算出x%9973的值,也就是(A/B)%9973的值。
利用擴充套件歐幾里德演算法可求出gcd(B,9973)=Bx1+9973y1=1的x1。題中說gcd(B,9973)=1;所以等式兩邊同乘以n,得B(nx1)-9973(-n
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
void extgcd(ll a, ll b, ll &x, ll &y) { // Bx - 9973y = 1 最後兩邊乘n
if (b == 0) {
x = 1;
y = 0;
return ;
} else {
extgcd(b, a%b, y, x);
y -= (a / b) * x;
}
}
int main() {
ll B, n, m;
cin >> m;
while (m--) {
cin >> n >> B;
ll x, y;
extgcd(B, 9973, x, y);
x *= n; // 兩邊同乘n
// x <= 0時 因為答案在0~9972內
x = (x%9973 + 9973) % 9973;
printf("%lld\n", x);
}
return 0;
}
數學分析法: 把所有未知的變數用已知的變數替換
思路:設X=(A/B)%9973
因為n=A%9973,所以A=k9973+n (k為一常數)
又因為X=(A/B)%9973,所以A/B=d9973+X (d為一常數)
兩邊同乘以B,得:A=Bd9973+BX
又因為 A = k9973 + n;
k9973 + n = Bd9973 + Bx
把n移到右邊:
k9973 = Bd9973 + Bx - n
所以題意轉為 只要滿足(B*X-n)%9973=0,X即為要求的結果。n的值知道,B的值知道,又因為x的取值範圍是0到9972,因此列舉x的值即可,滿足條件的就是答案。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
typedef long long ll;
using namespace std;
int main() {
ll B, n, m, i;
cin >> m;
while (m--) {
cin >> n >> B;
for (i = 0; i <= 9972; i++)
if ((B*i-n) % 9973 == 0) break;
cout << i << "\n";
}
return 0;
}