forked from philona/cppcodes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodularMultiplicativeInverse.cpp
More file actions
47 lines (43 loc) · 1.16 KB
/
modularMultiplicativeInverse.cpp
File metadata and controls
47 lines (43 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~
--||author : codechaser||--
~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <bits/stdc++.h>
using namespace std;
#define llint long long
// this algorithm uses extended euclidean as it's base and calculates
// modular multiplicative inverse of 'a' under mod 'b';
//MODULAR MULTIPLICATIVE INVERSE
//(i) Extended Euclidean Algorithm
llint gcdExt(llint a, llint b, llint& x, llint& y){
if(!a){
x=0,y=1;
return b;
}
llint x1,y1,g=gcdExt(b%a,a,x1,y1);
y=x1;
x=y1-(b/a)*y;
return g;
}
//(ii) Modular Multiplicative Inverse
//returns modular multiplicative inverse of 'a' under mod 'b';
llint modInv(llint a, llint b){
llint x,y;
gcdExt(a,b,x,y);
return x%b;
}
//NOTE:- makes sense iff gcd(a,b)==1;
int main(){
llint a,b,x,y;
cin>>a>>b;
cout<<a<<" * "<<modInv(a,b)<<" = 1 (mod "<<b<<")\n";
return 0;
}
/*
|---------------------------------------------------|
||| https://codeforces.com/profile/codechaser |||
||| https://www.codechef.com/users/codechaser |||
||| https://github.com/code-chaser |||
|---------------------------------------------------|
*/