[複習][NOIP2012真題]拓展歐幾里得 同餘方程

題目背景
NOIP2012 提高組 DAY2 試題。

題目描述
求關於 x 的同餘方程 ax ≡ 1 (mod b)的最小正整數解。

輸入格式
輸入只有一行,包含兩個正整數 a, b,用一個空格隔開。

輸出格式
輸出只有一行,包含一個正整數x0 ,即最小正整數解。輸入數據保證一定有解。

樣例數據
輸入

3 10

輸出

7

備註
【數據範圍】
對於 40% 的數據,2≤b≤1,000;
對於 60% 的數據,2≤b≤50,000,000;
對於 100% 的數據,2≤a,b≤2,000,000,000。

分析:拓展歐幾里得模板,如果不懂拓展歐幾里得,詳見zhj5chengfeng的博客

代碼

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<iomanip>
#include<queue>
#include<set>
using namespace std;

int getint()
{
    int sum=0,f=1;
    char ch;
    for(ch=getchar();!isdigit(ch)&&ch!='-';ch=getchar());
    if(ch=='-')
    {
        f=-1;
        ch=getchar();
    }
    for(;isdigit(ch);ch=getchar())
        sum=(sum<<3)+(sum<<1)+ch-48;
    return sum*f;
}

void exgcd(int a,int b,int &x,int &y)//x、y帶&號表示在exgcd函數中x、y發生變化,主程序中x、y也會跟着變
{
    if(!b)
    {
        x=1,y=0;
        return;
    }

    exgcd(b,a%b,x,y);
    int tmp=x;
    x=y,y=tmp-a/b*y;
}

int main()
{
    freopen("exgcd.in","r",stdin);
    freopen("exgcd.out","w",stdout);

    int x,y,a,b;
    a=getint(),b=getint();
    exgcd(a,b,x,y);
    cout<<(x%b+b)%b<<'\n';
    return 0;
}

本題結。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章