Skip to content

Commit 7577530

Browse files
author
monad
committed
added a program to calculate the modular multiplicative inverse
1 parent e9e6b57 commit 7577530

File tree

1 file changed

+48
-0
lines changed
  • Math/modular_multiplicative_inverse

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*computes the modular multiplicative inverse:
2+
* let x,n be any positive integers
3+
* we want to compute m so that:
4+
* (m*x)%n=1
5+
* i.e. the multiplicative inverse mod n
6+
*/
7+
8+
#include <iostream>
9+
10+
int inverse(int x, int n){
11+
int t=0;
12+
int r=n;
13+
int newt=1;
14+
int newr=x;
15+
while(newr!=0){
16+
int quot=r/newr;
17+
int tmp=newt;
18+
newt=t-quot*newt;
19+
t=tmp;
20+
tmp=newr;
21+
newr=r-quot*newr;
22+
r=tmp;
23+
}
24+
if(r>1){
25+
return -1;
26+
}
27+
if(t<0){
28+
t+=n;
29+
}
30+
return t;
31+
}
32+
33+
34+
int main(int argc, char** argv){
35+
if(argc!=3){
36+
std::cout<<"usage is: mmi x n\nwhere x denotes the given number and n denotes the mod"<<std::endl;
37+
return -1;
38+
}
39+
int x=std::stoi(argv[1]);
40+
int n=std::stoi(argv[2]);
41+
int result=inverse(x,n);
42+
if(result==-1){
43+
std::cout<<"not invertible"<<std::endl;
44+
return -1;
45+
}
46+
std::cout<<"inverse is: "<<result<<std::endl;
47+
return 0;
48+
}

0 commit comments

Comments
 (0)