Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdio>
- using namespace std;
- /// Greatest Common Divisor
- int gcd(int a, int b) {
- if (a < b)
- swap(a, b);
- if (b == 0)
- return a;
- else
- return gcd(b, a%b);
- }
- /// Summation A+B
- int sum(int a, int b, int m) {
- return (a%m + b%m)%m;
- }
- /// Multiplication A*B
- int mult(int a, int b, int m) {
- return (a%m * b%m)%m;
- }
- /// Exponentiation A^B
- int pow(int a, int b, int m) {
- int answer = 1;
- for (int i=0; i<b; i++)
- answer = mult(answer, a, m);
- return answer;
- }
- /// Fast Exponentiation A^B
- int pow_fast(int a, int b, int m) {
- if (b == 1)
- return a%m;
- int temp = pow_fast(a, b/2, m);
- if (b%2 == 0)
- return mult(temp, temp, m);
- else
- return mult(a, mult(temp, temp, m), m);
- }
- /// Euler's Function phi(n)
- /// Counts the positive numbers <= n that are co-prime to n
- int phi(int n) {
- int answer = 0;
- for (int i=1; i<n; i++)
- if (gcd(n, i) == 1)
- answer++;
- return answer;
- }
- /// Opposite element
- /// a*x = 1 (mod m)
- /// a^(phi(m)) = 1 (mod m) for co-prime numbers a and m <- Euler's Theorem
- /// So x = a^(phi(m) - 1) (mod m)
- int opp(int a, int m) {
- if (gcd(a, m) != 1) {
- cout << "There isn't opposite element";
- return m;
- }
- return pow(a, phi(m)-1, m);
- }
- /// Division is multiplication with an opposite element
- int div(int a, int b, int m) {
- return mult(a, opp(b, m), m);
- }
- int main()
- {
- int a, b, m;
- cin >> a >> b >> m;
- printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
- printf("%d + %d mod %d = %d\n", a, b, m, sum(a, b, m));
- printf("%d * %d mod %d = %d\n", a, b, m, mult(a, b, m));
- printf("%d ^ %d mod %d = %d\n", a, b, m, pow(a, b, m));
- printf("%d ^ %d mod %d = %d (fast)\n", a, b, m, pow_fast(a, b, m));
- printf("%d / %d mod %d = %d\n", a, b, m, div(a, b, m));
- printf("phi(%d) = %d\n", a, phi(a));
- printf("phi(%d) = %d\n", b, phi(b));
- printf("phi(%d) = %d\n", m, phi(m));
- printf("opposite element for %d is %d (mod %d)\n", a, opp(a, m), m);
- printf("opposite element for %d is %d (mod %d)\n", b, opp(b, m), m);
- return 0;
- }
Add Comment
Please, Sign In to add comment