【數學 逆元】zoj 3609 Modular Inverse


#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;

int x,y,q;

void extend_Eulid(int a,int b)
{
    if(b == 0)
    {
        x = 1;
        y = 0;
        q = a;
    }
    else
    {
        extend_Eulid(b,a%b);
        int temp = x;
        x = y;
        y = temp - a/b*y;
    }
}

int gcd(int a, int b)
{
    if(b == 0)
        return a;
    return gcd(b, a % b);

}

int main()
{
    int t;
    while(scanf("%d", &t) != EOF)
    {
        for(int i=0; i<t; i++)
        {
            int a, m;
            scanf("%d%d", &a, &m);
            if (m ==  1)
            {
                printf("1\n");
                continue;
            }
            if(gcd(a, m) != 1)
            {
                puts("Not Exist");
                continue;
            }
            extend_Eulid(a,m);
            x += m;
            x %= m;
            printf("%d\n",x);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章