uva 10104 (擴充歐幾裡德演算法)

來源:互聯網
上載者:User

    今天粗略學習了擴充歐幾裡德演算法。

  設a,b,c為任意整數,g=gcd(a,b),方程 ax+by=g的一組解是(x1,y1),則當c是g的倍數時,ax+by=c的一組解是(x1*c/g,y1*c/g);當c不是g的倍數時無整數解。

UVA 10104:

he Problem

From Euclid it is known that for any positive integers A and B there exist such integers X and Y thatAX+BY=D, where D is the greatest common divisor of A and B.
The problem is to find for given A and Bcorresponding XY and D.

The Input

The input will consist of a set of lines with the integer numbers A and B, separated with space (A,B<1000000001).

The Output

For each input line the output line should consist of three integers X, Y and D, separated with space. If there are several such X and Y, you should output that pair for which |X|+|Y| is
the minimal (primarily) and X<=Y (secondarily).

Sample Input

4 617 17

Sample Output

-1 1 20 1 17


代碼:

#include<cstdio>
void gcd(int a,int b,int &d,int &x,int &y)
{
    if(b==0)
    {
        d=a;
        x=1;y=0;
    }
    else
    {
        gcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}
using namespace std;
int main()
{

    int a,b,d,x,y;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
         gcd(a,b,d,x,y);
         printf("%d %d %d\n",x,y,d);
    }
    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.