Pagini recente » Cod sursa (job #2780728) | Cod sursa (job #855049) | Cod sursa (job #583184) | Cod sursa (job #1324138) | Cod sursa (job #3225641)
#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;
}