gerkulesov

Modulo operations

May 17th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. using namespace std;
  4.  
  5. /// Greatest Common Divisor
  6. int gcd(int a, int b) {
  7.     if (a < b)
  8.         swap(a, b);
  9.     if (b == 0)
  10.         return a;
  11.     else
  12.         return gcd(b, a%b);
  13. }
  14.  
  15. /// Summation A+B
  16. int sum(int a, int b, int m) {
  17.     return (a%m + b%m)%m;
  18. }
  19.  
  20. /// Multiplication A*B
  21. int mult(int a, int b, int m) {
  22.     return (a%m * b%m)%m;
  23. }
  24.  
  25. /// Exponentiation A^B
  26. int pow(int a, int b, int m) {
  27.     int answer = 1;
  28.     for (int i=0; i<b; i++)
  29.         answer = mult(answer, a, m);
  30.     return answer;
  31. }
  32.  
  33. /// Fast Exponentiation A^B
  34. int pow_fast(int a, int b, int m) {
  35.     if (b == 1)
  36.         return a%m;
  37.  
  38.     int temp = pow_fast(a, b/2, m);
  39.     if (b%2 == 0)
  40.         return mult(temp, temp, m);
  41.     else
  42.         return mult(a, mult(temp, temp, m), m);
  43. }
  44.  
  45. /// Euler's Function phi(n)
  46. /// Counts the positive numbers <= n that are co-prime to n
  47. int phi(int n) {
  48.     int answer = 0;
  49.     for (int i=1; i<n; i++)
  50.         if (gcd(n, i) == 1)
  51.             answer++;
  52.     return answer;
  53. }
  54.  
  55. /// Opposite element
  56. /// a*x = 1 (mod m)
  57. /// a^(phi(m)) = 1 (mod m) for co-prime numbers a and m <- Euler's Theorem
  58. /// So x = a^(phi(m) - 1) (mod m)
  59. int opp(int a, int m) {
  60.     if (gcd(a, m) != 1) {
  61.         cout << "There isn't opposite element";
  62.         return m;
  63.     }
  64.     return pow(a, phi(m)-1, m);
  65. }
  66.  
  67. /// Division is multiplication with an opposite element
  68. int div(int a, int b, int m) {
  69.     return mult(a, opp(b, m), m);
  70. }
  71.  
  72. int main()
  73. {
  74.     int a, b, m;
  75.     cin >> a >> b >> m;
  76.  
  77.     printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
  78.     printf("%d + %d mod %d = %d\n", a, b, m, sum(a, b, m));
  79.     printf("%d * %d mod %d = %d\n", a, b, m, mult(a, b, m));
  80.     printf("%d ^ %d mod %d = %d\n", a, b, m, pow(a, b, m));
  81.     printf("%d ^ %d mod %d = %d (fast)\n", a, b, m, pow_fast(a, b, m));
  82.     printf("%d / %d mod %d = %d\n", a, b, m, div(a, b, m));
  83.     printf("phi(%d) = %d\n", a, phi(a));
  84.     printf("phi(%d) = %d\n", b, phi(b));
  85.     printf("phi(%d) = %d\n", m, phi(m));
  86.     printf("opposite element for %d is %d (mod %d)\n", a, opp(a, m), m);
  87.     printf("opposite element for %d is %d (mod %d)\n", b, opp(b, m), m);
  88.  
  89.     return 0;
  90. }
Add Comment
Please, Sign In to add comment