-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMOD Divide
More file actions
42 lines (36 loc) · 814 Bytes
/
MOD Divide
File metadata and controls
42 lines (36 loc) · 814 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
lli gcdExtended(lli a, lli b, lli *x, lli *y)
{
// Base Case
if (a == 0)
{
*x = 0, *y = 1;
return b;
}
lli x1, y1; // To store results of recursive call
lli gcd = gcdExtended(b%a, a, &x1, &y1);
// Update x and y using results of recursive
// call
*x = y1 - (b/a) * x1;
*y = x1;
return gcd;
}
//m=MOD
lli modInverse(lli b, lli m)
{
lli x, y; // used in extended GCD algorithm
lli g = gcdExtended(b, m, &x, &y);
// Return -1 if b and m are not co-prime
if (g != 1)
return -1;
// m is added to handle negative x
return (x%m + m) % m;
}
lli modDivide(lli a, lli b, lli m)
{
a = a % m;
lli inv = modInverse(b, m);
if (inv == -1)
return -1;
else
return (inv * a) % m;
}