拓展欧几里德算法求逆元2

 1 void gcd(int a,int b,int &d,int &x,int &y)
 2 {
 3     if(!b)
 4     {
 5         d=a;
 6         x=1;
 7         y=0;
 8     }
 9     else
10     {
11         gcd(b,a%b,y,x);
12         y-=x*(a/b);
13     }
14 }
15 
16 //计算模n下a的逆元,如果不存在逆元,返回-1
17 int inv(int a,int n)
18 {
19     int d,x,y;
20     gcd(a,n,d,x,y);
21     return d==1? (x+n)%n: -1;
22 }
View Code

 公式:

(a/b)%c=((a%c)*b^(-1)%c)

 

posted @ 2015-07-24 18:05  相儒以沫  阅读(137)  评论(0编辑  收藏  举报