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?
Asked
Active
Viewed 2,292 times
-2
-
4What do you mean by inverse? 10 -> .1 or 10 -> 1? – NathanOliver Dec 17 '18 at 18:36
-
1additive inverse of multiplicative inverse? – Adham Zahran Dec 17 '18 at 18:37
-
multiplicative inverse – mone Dec 17 '18 at 18:42
-
1@mone `1/a` assuming `a` is your number – Aykhan Hagverdili Dec 17 '18 at 18:44
-
1Did you do any research on this? – Lightness Races in Orbit Dec 17 '18 at 18:50
-
https://stackoverflow.com/q/7207391/2785528 - is about the ~ operator ... which is a bitwise NOT, it inverts the bits in a binary number. – 2785528 Dec 17 '18 at 20:04
-
The modular multiplicative inverse you need for RSA (including a sample implementation for small numbers) has been [discussed previously](https://stackoverflow.com/a/20114154/179910). – Jerry Coffin Dec 17 '18 at 20:07
1 Answers
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:

sideshowbarker
- 81,827
- 26
- 193
- 197

paulsm4
- 114,292
- 17
- 138
- 190