Skip to content

Commit

Permalink
Merge pull request matthewsamuel95#37 from stuxxnet42/master
Browse files Browse the repository at this point in the history
added a program to calculate the modular multiplicative inverse
  • Loading branch information
matthewsamuel95 authored Oct 22, 2017
2 parents 58f1978 + 7577530 commit 0f9bd2d
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Math/modular_multiplicative_inverse/mmi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*computes the modular multiplicative inverse:
* let x,n be any positive integers
* we want to compute m so that:
* (m*x)%n=1
* i.e. the multiplicative inverse mod n
*/

#include <iostream>

int inverse(int x, int n){
int t=0;
int r=n;
int newt=1;
int newr=x;
while(newr!=0){
int quot=r/newr;
int tmp=newt;
newt=t-quot*newt;
t=tmp;
tmp=newr;
newr=r-quot*newr;
r=tmp;
}
if(r>1){
return -1;
}
if(t<0){
t+=n;
}
return t;
}


int main(int argc, char** argv){
if(argc!=3){
std::cout<<"usage is: mmi x n\nwhere x denotes the given number and n denotes the mod"<<std::endl;
return -1;
}
int x=std::stoi(argv[1]);
int n=std::stoi(argv[2]);
int result=inverse(x,n);
if(result==-1){
std::cout<<"not invertible"<<std::endl;
return -1;
}
std::cout<<"inverse is: "<<result<<std::endl;
return 0;
}

0 comments on commit 0f9bd2d

Please sign in to comment.