spider68

MOD DIVISION (a/b)%m

Apr 3rd, 2020
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. // C++ program to do modular division
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. // C function for extended Euclidean Algorithm
  6. int gcdExtended(int a, int b, int *x, int *y);
  7.  
  8. // Function to find modulo inverse of b. It returns
  9. // -1 when inverse doesn't
  10. int modInverse(int b, int m)
  11. {
  12.     int x, y; // used in extended GCD algorithm
  13.     int g = gcdExtended(b, m, &x, &y);
  14.  
  15.     // Return -1 if b and m are not co-prime
  16.     if (g != 1)
  17.         return -1;
  18.  
  19.     // m is added to handle negative x
  20.     return (x%m + m) % m;
  21. }
  22.  
  23. // Function to compute a/b under modlo m
  24. void modDivide(int a, int b, int m)
  25. {
  26.     a = a % m;
  27.     int inv = modInverse(b, m);
  28.     if (inv == -1)
  29.     cout << "Division not defined";
  30.     else
  31.     cout << "Result of division is " << (inv * a) % m;
  32. }
  33.  
  34. // C function for extended Euclidean Algorithm (used to
  35. // find modular inverse.
  36. int gcdExtended(int a, int b, int *x, int *y)
  37. {
  38.     // Base Case
  39.     if (a == 0)
  40.     {
  41.         *x = 0, *y = 1;
  42.         return b;
  43.     }
  44.  
  45.     int x1, y1; // To store results of recursive call
  46.     int gcd = gcdExtended(b%a, a, &x1, &y1);
  47.  
  48.     // Update x and y using results of recursive
  49.     // call
  50.     *x = y1 - (b/a) * x1;
  51.     *y = x1;
  52.  
  53.     return gcd;
  54. }
  55.  
  56. // Driver Program
  57. int main()
  58. {
  59.     int a = 8, b = 3, m = 5;
  60.     modDivide(a, b, m);
  61.     return 0;
  62. }
Add Comment
Please, Sign In to add comment