Cod sursa(job #3296951)

Utilizator christalknightChristian Micea christalknight Data 19 mai 2025 11:58:53
Problema Invers modular Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
// https://infoarena.ro/problema/inversmodular

#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("inversmodular.in");
ofstream fout("inversmodular.out");

unsigned long long exponentiate(unsigned long long n, unsigned long long p, unsigned long long mod)  //computes and returns n to the power of p
{
    if (p == 0)
        return 1;

    if (p % 2) // p is odd
        return (n * exponentiate((n * n) % mod, (p - 1) / 2, mod)) % mod;
    else // p is even
        return exponentiate((n * n) % mod, p / 2, mod);
} 

long long int compute_phi(long long int n) // Euler's theorem (teorema lui Euler)
{
    long long int result = n;

	for (long long int i = 2; i * i <= n; i++) {
		if (n % i == 0) {
			while (n % i == 0)
                n /= i;
			result = (result / i) * (i - 1);
		}
	}
    
    if (n != 1) 
        result = result / n * (n - 1);
	
    return result;
}

int main(){
    int a, n;

    fin >> a >> n;

    fout << exponentiate(a, compute_phi(n) - 1, n) % n;

    fin.close();
    fout.close();
    return 0;
}

void greatest_common_divisor(long long int &x, long long int &y, int a, int n)
{  
    if (n == 0) {
        x = 1;
        y = 0;  
    }
    else {             
        greatest_common_divisor(x, y, n, a % n);
        long long int aux = x;
        x = y;
        y = aux - y * (a / n);
    }
}