同餘方程(擴充套件歐幾里德演算法)
阿新 • • 發佈:2018-12-06
同餘方程
時間限制: 1 Sec 記憶體限制: 128 MB
題目描述
求關於 x 的同餘方程 ax ≡ 1 (mod b)的最小正整數解。
輸入
輸入只有一行,包含兩個正整數 a, b,用一個空格隔開。
輸出
輸出只有一行,包含一個正整數 x0,即最小正整數解。輸入資料保證一定有解。
樣例輸入
複製樣例資料
3 10
樣例輸出
7
提示
對於 100%的資料,2 ≤a, b≤ 2,000,000,000。
ax≡1(mod b) -> ax%b - 1%b≡0,因為b大於2,所以ax%b=1,馬上想到ax=by+1,即ax-by=1,這不就是擴充套件歐幾里德嗎?
把a求出來,因為a有可能為負的,但題目要正的,那麼怎麼辦呢,可以問by借點(x+mb)a+b(y-ma)=1還是成立的,所以只要在x上加m倍的b就行了。
/**/ #include <cstdio> #include <cstring> #include <cmath> #include <cctype> #include <iostream> #include <algorithm> #include <map> #include <set> #include <vector> #include <string> #include <stack> #include <queue> typedef long long LL; using namespace std; LL a, b; LL ans; void ex_gcd(LL a, LL b, LL &x, LL &y){ if(!b){ x = 1, y = 0; return ; } ex_gcd(b, a % b, y, x); y -= x * (a / b); } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); scanf("%lld %lld", &a, &b); LL x, y; ex_gcd(a, b, x, y); while(x < 0) x += b; printf("%lld\n", x); return 0; } /**/