求乘法逆元

来源:互联网 发布:mysql增加primary key 编辑:程序博客网 时间:2024/04/27 21:26

                                               乘法逆元的求法  

        对于不定整数方程pa+qb=c,若 c mod Gcd(a, b)=0,则该方程存在整数解,否则不存在整数解。

        在找到p * a+q * b = Gcd(a, b)的一组解p0,q0后,p * a+q * b = Gcd(a, b)的其他整数解满足:   p = p0 + b/Gcd(a, b) * t   q = q0 - a/Gcd(a, b) * t(其中t为任意整数)

        至于pa+qb=c的整数解,只需将p * a+q * b = Gcd(a, b)的每个解乘上 c/Gcd(a, b) 即可。  在找到p * a+q * b = Gcd(a, b)的一组解p0,q0后,应该是   得到p * a+q * b = c的一组解p1 = p0*(c/Gcd(a,b)),q1 = q0*(c/Gcd(a,b)),p * a+q * b = c的其他整数解满足:   p = p1 + b/Gcd(a, b) * t   q = q1 - a/Gcd(a, b) * t(其中t为任意整数)   p 、q就是p * a+q * b = c的所有整数解。

只有两个数互质的时候才存在乘法逆元,即c=1。

 

例:求5的模7逆

做辗转相除法, 求得整数b,k使得 5p+7q=1, 则p是5的模7逆,q是7的模5逆。

计算如下:

     7=5+2,  5=2×2+1.

回代    1=5-2×2=5-2×(7-5)= 3×5-2×7,

得 5^ -1≡3(mod7).(其中“^”是次方的意思)

例:求21的模73逆

做辗转相除法, 求得整数b,k使得 21p+73q=1, 则p是21的模73逆,q是73的模21逆。

计算如下:

     73=21*3+10

21=10*2+1

回代    1=21-10*2

1=21-(73-21*3)*2

=21-73*2+6*21

=7*21-73*2

得 21^ -1≡7(mod73). (其中“^”是次方的意思)

 

求乘法逆元的代码:

#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;}


0 0
原创粉丝点击