文章目录
欧拉函数
#include <iostream>
using namespace std;
#include<algorithm>
int test_01()
{
int n;
cin >> n;
while(n --)
{
int a;
cin >> a;
int res = a;
for(int i = 2;i <= a / i;i ++)
if(a % i == 0)
{
res = res / i * (i - 1);
while(a % i == 0) a /= i;
}
if(a > 1) res = res / a * (a - 1);
}
return 0;
}
874. 筛法求欧拉函数
const int N = 1000010;
typedef long long LL;
int primes[N],cnt;
int phi[N];
bool st[N];
LL get_eulers(int n)
{
phi[1] = 1;
for(int i = 2; i <= n;i++)
{
if(!st[i])
{
primes[cnt ++] = i;
phi[i] = i - 1;
}
for(int j = 0; primes[j] <= n / i;j++)
{
st[primes[j] * i] = true;
if(i % primes[j] == 0)
{
phi[primes[j] * i] = phi[i] * primes[j];
break;
}
phi[primes[j] * i] = phi[i] * (primes[j] - 1);
}
}
LL res = 0;
for(int i = 1 ;i <= n ; i++) res += phi[i];
return res;
}
int test_02()
{
int n;
cin >> n;
cout << get_eulers(n) << endl;
return 0;
}
875. 快速幂 O(logk)
#include<algorithm>
typedef long long LL;
LL qmi(int a,int k,int p)
{
int res = 1;
while(k)
{
if(k & 1)res = (LL)res * a % p;
k >>= 1;
a = (LL)a * a % p;
}
return res;
}
int test_03()
{
int n;
scanf("%d",&n);
while(n --)
{
int a,k,p;
scanf("%d%d%d",&a,&k,&p);
printf("%lld\n",qmi(a,k,p));
}
return 0;
}
876. 快速幂求逆元
逆元:
typedef long long LL;
#include<cstdio>
LL qmi(int a,int k,int p)
{
LL res = 1;
while(k)
{
if(k & 1) res = (LL)res * a % p;
k >>= 1;
a = (LL)a * a % p;
}
return res;
}
int test_04()
{
int n;
scanf("%d",&n);
while(n --)
{
int a,k,p;
scanf("%d%d",&a,&p);
LL res = qmi(a,p-2,p);
if(a % p)printf("%lld",res);
else puts("impossible");
}
return 0;
}
877. 扩展欧几里得算法
int gcd(int a,int b)
{
if(b == 0)return a;
return gcd(b,a%b);
}
int exgcd(int a,int b,int &x,int &y)
{
if(!b)
{
x = 1,y = 0;
return a;
}
int d = exgcd(b,a%b,y,x);
y -= a / b * x;
return d;
}
int test_05()
{
int n;
scanf("%d",&n);
while(n --)
{
int a,b,x,y;
scanf("%d%d",&a,&b);
exgcd(a,b,x,y);
printf("%d %d\n",x,y);
}
return 0;
}
int test_06()
{
int n;
scanf("%d",&n);
while(n --)
{
int a,b,m;
scanf("%d%d%d",&a,&b,&m);
int x,y;
int d = exgcd(a,m,x,y);
if(b % d) puts("impossible");
else printf("%d\n",(LL)x * (b / d) % m);
}
return 0;
}
int main() {
test_06();
return 0;
}