【codevs1200】 NOIP2012—同餘方程

codevs.cn/problem/1200/ (題目鏈接)

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

Solution
  
  這道題其實就是求a mod b的逆元x。所謂逆元其實很簡單,記a的關於模p的逆
元爲a^-1,則a^-1滿足aa^-1≡ 1(mod p),用擴展歐幾里德即可。
  關於擴展歐幾里德,有博客寫了證明:blog.csdn.net/lincifer/article/details/49391175
  
代碼:

// codevs1200
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define inf 2147483640
#define Pi 3.1415926535898
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;



void exgcd(LL a,LL b,LL &x,LL &y) {
    if (b==0) {x=1;y=0;return;}
    exgcd(b,a%b,x,y);
    LL t=x;x=y;y=t-a/b*y;
}
int main() {
    LL x,y,a,b;
    scanf("%lld%lld",&a,&b);
    exgcd(a,b,x,y);
    printf("%lld",(x+b)%b);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章