Cod sursa(job #3225641)

Utilizator Andrei_RusuAndrei Alexandru Rusu Andrei_Rusu Data 18 aprilie 2024 12:21:11
Problema Invers modular Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>
#include <iostream>

using namespace std;
ifstream fin("inversmodular.in");
ofstream fout("inversmodular.out");
bool prim(int n)
{
    if(n<2 || !(n&1) && n!=2)
        return 0;
    if(n==2)
        return 1;
    for(int d=3; d*d<=n; d+=2)
        if(n%d==0)
            return 0;
    return 1;
}
long long fastExpo(int p, int e, int mod)
{
    long long sol=1, a=p%mod;
    for(int k=1; k<=e; k<<=1)
    {
        if(e&k) sol*=a%mod;
        a*=a%mod;
    }
    return sol%mod;
}
void euclid(int a, int b, int &d, int &x, int &y)
{
    if(b==0)
    {
        d=a;
        x=1;
        y=0;
    }
    else
    {
        int x0, y0;
        euclid(b,a%b,d,x0,y0);
        x=y0;
        y=x0-(a/b)*y0;
    }
}
int main()
{
    int a, n,d,x,y;

    fin >> a >> n;
    if(prim(n))
    {
        fout << fastExpo(a,n-2,n);
    }
    else
    {

        euclid(a,n,d,x,y);
        fout << x%n;
    }
    return 0;
}