Cod sursa(job #2016844)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 30 august 2017 17:03:01
Problema Invers modular Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
ifstream f("inversmodular.in");
ofstream g("inversmodular.out");
long long a,n,p,t;
long long prim(long long x)
{
    if(x==0 || x==1)
    {
        return 0;
    }
    if(x%2==0 && x!=2)
    {
        return 0;
    }
    long long i=3;
    while(i<=sqrt(x))
    {
        if(x%i==0)
        {
            return 0;
        }
        i=i+2;
    }
    return 1;
}
long long fi(long long x)
{
    long long rez,i;
    rez=x;
    for(i=2;i*i<=x;i++)
    {
        if(x%i==0)
        {
        while(x%i==0)
        {
            x=x/i;
        }
        rez=(rez/i)*(i-1);
        }
    }
    if(x!=1)
    {
        rez=(rez/x)*(x-1);
    }
    return rez;
}
int main()
{
    f>>a>>n;
    if(prim(n)==1)
    {
        t=n-2;
    }
    else
    {
        t=fi(n)-1;
    }
    p=1;
    while(t>0)
    {
        if(t%2!=0)
        {
            p=(p*a)%n;
        }
        a=(a*a)%n;
        t=t/2;
    }
    g<<p;
    return 0;
}