int MainWindow::modInverse(int a, int m) { int x, y; int res = 0; int gcd = gcdExtended(a, m, &x, &y); if (gcd == 1) res = (x%m + m) % m; return res; }
//modular inverse works like GCD, but returns different value long ModInverse(long a, long m){ int x, y; long g = gcdExtended(a, m, &x, &y); if (g != 1) printf( "Inverse doesn't exist\n"); else{ // m is added to handle negative x long res = (x%m + m) % m; return res; } return -1; }
int algebra::gcdExtended(int a, int b, int &x, int &y) { if(a == 0) { x = 0; y = 1; return b; } int x1, y1; int d = gcdExtended(b%a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return d; }
int MainWindow::gcdExtended(int a, int b, int *x, int *y) { if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; int gcd = gcdExtended(b%a, a, &x1, &y1); *x = y1 - (b/a) * x1; *y = x1; return gcd; }
//function for extended Euclidean Algorithm 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; }