-2

Im working on a RSA code and I rly dont know how to do the inverse of a number on c++. How you would you do it? There are some librarys that can help me to do it automatically?

mone
  • 27
  • 1

1 Answers1

3

Here are several examples for Modular multiplicative inverse in C++:

https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/

// C++ program to find multiplicative modulo inverse using 
// Extended Euclid algorithm. 
#include<iostream> 
using namespace std; 
  
// C function for extended Euclidean Algorithm 
int gcdExtended(int a, int b, int *x, int *y); 
  
// Function to find modulo inverse of a 
void modInverse(int a, int m) 
{ 
    int x, y; 
    int g = gcdExtended(a, m, &x, &y); 
    if (g != 1) 
        cout << "Inverse doesn't exist"; 
    else
    { 
        // m is added to handle negative x 
        int res = (x%m + m) % m; 
        cout << "Modular multiplicative inverse is " << res; 
    } 
} 
  
// C 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; 
} 
  
// Driver Program 
int main() 
{ 
    int a = 3, m = 11; 
    modInverse(a, m); 
    return 0; 
}

Here's a good description of what it's doing:

Modular multiplicative inverse

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
paulsm4
  • 114,292
  • 17
  • 138
  • 190