UVa Problem 10104 Euclid Problem (歐幾裡德問題)

來源:互聯網
上載者:User
// Euclid Problem (歐幾裡德問題)// PC/UVa IDs: 110703/10104, Popularity: A, Success rate: average Level: 1// Verdict: Accepted// Submission Date: 2011-06-10// UVa Run Time: 0.684s//// 著作權(C)2011,邱秋。metaphysis # yeah dot net//// 根據 Euclid 求 GCD 的過程,可以找到兩個數 x 和 y,使得://// a * x + b * y = GCD(a, b)(1)//// 由於 GCD(a, b) = GCD(b, a'),其中 a' = a - b * [a / b],根據數學歸納法,假設// 已經找到了整數 x' 和 y',使得://// b * x' + a' * y' = GCD(a, b)(2)//// 把 a' 的運算式代入(2)式,得到://// b * x' + (a - b * [a / b]) * y' = GCD(a, b)(3)//// 起始條件是: a * 1 + 0 * 0 = GCD(a, 0),整理可得到://// x = y'// y = x' - b * [a / b] * y'//// 由以上可以得到方程 (1) 的一組解,由於方程 (1) 和同餘方程 a * x ≡ GCD(a, b) (mod b)// 是等價的,而通過 Euclid 求 GCD 的過程可以得到同餘方程的一個解 y',則所有解可表示為://// x = y' + k * b / GCD(a, b)// y = (GCD(a, b) - a * y' - a * k * b / GCD(a, b)) / b//// 其中 k 為任意整數。由於已經限定 a 和 b 都為正整數,可以不需考慮 a 或(和) b 為 0 的情況。// 由於 GCD(a, b) <= min(a, b),故 x 和 y 必有 min(x, y) <= 0,max(x, y) > 0。//// 可以將求 GCD 的過程進行擴充,得到相應的解,輸出即可達到要求。演算法得到的 x 和 y 即是絕對值和// 最小的(這一點為什麼成立?因為起始條件 a * 1 + 0 * 0 = GCD(a, 0) 決定了它必將是絕對值和// 最小的)。另外題目的敘述有點讓人疑惑,應該是先考慮絕對值最小的,然後再考慮 x <= y 這個條件。#include <iostream>#include <cmath>using namespace std;long gcd(long a, long b, long *x, long *y){long tx, ty;long g;if (b > a)return gcd(b, a, y, x);if (b == 0){*x = 1;*y = 0;return a;}g = gcd(b, a % b, &tx, &ty);*x = ty;*y = tx - floor(a / b) * ty;return g;}int main(int ac, char *av[]){long a, b;long g;long x, y;while (cin >> a >> b){g = gcd(a, b, &x, &y);cout << x << " " << y << " " << g << endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.