#ifndef __MOD_DIVIDE_H__ #define __MOD_DIVIDE_H__ using namespace std; int modInverse1(int A, int M) { int m0 = M; int y = 0, x = 1; if (M == 1) return 0; while (A > 1) { // q is quotient int q = A / M; int t = M; // m is remainder now, process same as // Euclid's algo M = A % M, A = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } int modular_inverse(int a, int m) { for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return 0; } // C++ function for extended Euclidean Algorithm int gcdExtended(int a, int b, int *x, int *y); // Function to find modulo inverse of b. It returns // -1 when inverse doesn't int modInverse(int b, int m) { int x, y; // used in extended GCD algorithm int 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; } // Function to compute a/b under modulo m int modDivide(int a, int b, int m) { a = a % m; int inv = modInverse(b, m); if (inv == -1) { cout << "Division not defined for " << a << "/" << b << endl; return -1; } else { cout << "Result of division is " << (inv * a) % m << endl; return (inv * a ) % m; } } // C function for extended Euclidean Algorithm (used to // find modular inverse. int gcdExtended(int a, int b, int *x, int *y) { // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int 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; } #endif