乘法逆元

求乘法逆元的代碼:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string.h>
#include <math.h>

using namespace std;

int gcd(int a,int b,int &x,int &y)
{
    int ans;
    if(!b)
    {
        x=1;
        y=0;
        return a;
    }
    ans = gcd(b,a%b,x,y);
    int temp = x;
    x= y;
    y= temp - (a/b)*y;
    return ans;
}
int main()
{

///求ax+by=c的乘法逆元
    int a,b,c,x,y;
    int temp;
    while(scanf("%d%d%d",&a,&b,&c),a||b||c)
    {
        int ans_x,ans_y;///a,b的逆元
        ///c總爲1
        temp = gcd(a,b,x,y);
        if(c%temp)
        {
            printf("乘法逆元不存在!\n");
            continue;
        }
        ans_x = (x*c/temp) <0 ? x*c/temp+b : x*c/temp;
        ans_y = (y*c/temp) <0 ? y*c/temp+a : y*c/temp;
        printf("%d  %d\n",ans_x,ans_y);
        }
    return 0;
}


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