Pagini recente » Cod sursa (job #30708) | Cod sursa (job #1885275) | Cod sursa (job #2955305) | Cod sursa (job #1666775) | Cod sursa (job #3157132)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("inversmodular.in");
ofstream fout("inversmodular.out");
long long mod;
long long totient(long long n){
long long d = 3,res = n,p = 0;
if(n % 2 == 0){
while(!(n % 2)){
p++;
n >>= 1;
}
res /= 2;
}
while(n > 1){
if(n % d == 0){
p = 0;
while(!(n % d)){
p++;
n /= d;
}
res *= (d - 1);
res /= d;
}
if(d * d >= n)
d = n;
else d += 2;
}
return res;
}
long long exp(long long n, long long p){
if(p == 1) return n;
if(p & 1) return (exp(n,p - 1) * n) % mod;
long long x = exp(n,p / 2);
return (x * x) % mod;
}
int gcd(int a, int b, int &x, int &y){
if(!b){
x = 1;
y = 0;
return a;
}
int x0,y0;
int d = gcd(b,a % b,x0,y0);
x = y0;
y = x0 - (a / b) * y0;
return d;
}
int invmod1(int n, int m){
int x,y;
int d = gcd(n,m,x,y);
while(y < 0) y += m;
return y;
}
long long invmod2(long long n, long long m){
long long a = totient(m);
return exp(n,a - 1);
}
int main()
{
//cu alg euclid extins
long long n,m;
fin >> n >> m;
mod = m;
// fout << invmod1(n,m);
fout << invmod2(n,m);
return 0;
}