Cod sursa(job #2507674)

Utilizator nicu_ducalNicu Ducal nicu_ducal Data 10 decembrie 2019 17:57:04
Problema Invers modular Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>
typedef unsigned long long ul;
typedef long long ll;
using namespace std;

ll a, n, x;

ll phiCalc(ll n)
{
    float phi = n;
    for (ll p = 2; p * p <= n; p++)
    {
        if (n % p == 0)
        {
            while (n % p == 0) n /= p;
            phi *= (1.0 - (1.0 / (float)p));

        }
    }
    if (n > 1) phi *= (1.0 - (1.0 / (float)n));
    return (int) phi;
}

ll expon(ll b, ll p)
{
    if (p == 0) return 1;
    else if (p == 1) return b % n;
    else if (p % 2 == 0) return expon((b%n * b%n) % n, p / 2) % n;
    else if (p % 2 == 1) return (b % n) * (expon((b%n * b%n) % n, (p - 1) / 2) % n);
}

int main(){
ios_base::sync_with_stdio(0); cin.tie(); cout.tie();
ifstream cin("inversmodular.in");
ofstream cout("inversmodular.out");

cin >> a >> n;

cout << expon(a, phiCalc(n) - 1) % n << "\n";


return 0;
}