-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcd_euclidean_modular_inverse.cpp
More file actions
55 lines (43 loc) · 987 Bytes
/
Copy pathgcd_euclidean_modular_inverse.cpp
File metadata and controls
55 lines (43 loc) · 987 Bytes
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
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll gcd(ll a, ll b)
{
if (b == 0){return a; }
return gcd(b, a % b);
}
ll gcd_extended(ll a, ll b, ll& x, ll& y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
ll x1, y1;
ll d = gcd_extended(b, a % b, x1, y1);
x = y1;
y = x1 - y1 * (a / b);
return d;
}
ll mod_inverse(ll a, ll m){
ll x,y;
ll g = gcd_extended(a,m,x,y);
ll res= -1;
if(g!=1LL){cout<<"modular inverse does not exist\n";}
else{res = (x%m + m)%m;}
return res;
}
int main() {
cout<<gcd(7, 876543)<<"\n";
cout<<gcd(54, 888)<<"\n";
cout<<gcd(90, 6)<<"\n";
cout<<gcd(125348, 18)<<"\n";
cout<<"\n gcd_extended: ";
ll x,y;
cout<<gcd_extended(54, 888, x, y)<<"\n";
cout<<"x: "<<x<<"\n";
cout<<"y: "<<y<<"\n";
ll a=3;
ll m=11;
cout<<"modular inverse of "<<a<<" modulo "<<m<<" is: "<<mod_inverse(a,m);
return 0;
}