HDU 2669 擴充歐幾裡德求二元不定方程,超水..

來源:互聯網
上載者:User

看完數論數的這一段,覺得這個演算法太精闢了,其實擴充歐幾裡德演算法就是書上的公式翻譯成代碼,實在是太棒了,我還SB似的去糾結過程,其實自己已經會筆算了

可是書上的第二種解二元一次不定方程方法,目前還在糾結中...

運用的定理中的推論得出一定存在整數 x , y 使得 ax + by =gcd( a,b); 成立. 同樣有定理得到
如果 ax + by = n 有解,則 gcd( a,b ) | n 一定成立

令 a1 = a | gcd( a,b ); b1 = b | gcd( a,b ) ; n1 = n | gcd( a,b ) ; ( a1 , b1 ) =1 ; 所以 ax +by = n; 和 a1x + b1y = n1 ; 的解是一樣的, 所以要求 a1 x + b1y = n1 的通解

則必須求一特解,則就解方程 a1x + b1y=1; 解的解(x' , y' ) ,擴充解( x'+t*b1 , y'-t*a1 )t = 1,2,3,4,.... 利用數論書上第一章的定理來解方程..

則翻譯成代碼就成了 所謂的擴充歐幾裡得演算法...

 

注意題意最後是要你求 x 的最小正整數解...

#include<iostream>
using namespace std;

int kzgcd(int a,int b,int &x,int &y){
    if(b==0){ x=1,y=0; return a; }
    int res = kzgcd(b,a%b,y,x);
    y -= a/b*x;
    return res;
}

int main(){
    int n,m;
    while(cin>>n>>m){
        int x,y;
        int flag=kzgcd(n,m,x,y);
        if(flag!=1) {
            printf("sorry\n");
            continue;
        }
        while(x<0){  //// 對解的要求
            x += m;  //// 注意解的轉化
            y -= n;  //// 
        }
        printf("%d %d\n",x,y);
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.