Cod sursa(job #1469871)

Utilizator tudoras8tudoras8 tudoras8 Data 9 august 2015 19:55:12
Problema Invers modular Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
#include <iostream>

using namespace std;

int phi(int n) {
    float res = n;

    if (n % 2 == 0) {
        res *= 0.5;
    }
    while (n % 2 == 0) {
        n /= 2;
    }

    for (int p = 3; p * p <= n; p += 2) {
        if (n % p == 0) {
            while (n % p == 0) {
                n /= p;
            }
            res *= (1 - 1 / (float) p);
        }
    }

    if (n > 1) {
        res *= (1 - 1 / (float) n);
    }

    return (int) res;
}

int main()
{
    ifstream cin("inversmodular.in");
    ofstream cout("inversmodular.out");

    int a, n;
    cin >> a >> n;

    int put = phi(n) - 1, ans = 1, nr = a;
    for (int p = 1; p <= put; p <<= 1) {
        if (p & put) {
            ans = (ans * nr) % n;
        }
        nr = (nr * nr) % n;
    }
    cout << ans;

    return 0;
}