(本篇没有涉及公式的推导)
欧拉函数:
就是对于一个正整数n,小于n且和n互质的正整数的个数记做φ(n) 。
欧拉函数的通式:
φ(n) = n * ( 1 - 1 / p1) ( 1 - 1 / p2 ) ( 1 - 1 / p3 ) * ( 1 - 1 / p4 )……( 1 - 1 / pn )
其中p1,p2……pn为n的所有质因子,n是不为0的整数。(唯一和1互质的数就是1本身)。
所以根据通式可以打出以下代码:
ll eular(ll n)
{
ll ans=n;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
ans=ans/i*(i-1);
while(n%i==0)
n=n/i;
}
}
if(n>1) ans=ans/n*(n-1);
return ans;
}
欧拉定理:
在数论中,欧拉定理,(也称费马——欧拉定理)是一个关于同余的性质。欧拉定理表明,若n和a为正整数,且n,a互质,则:
欧拉降幂
第一个要求a和p互质,第二个和第三个是广义的欧拉降幂,但要求b和φ( p)的关系 。
模板:
求A^BmodC
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e6+10;
char b[N];
LL a,c;
LL quick_pow(LL x,LL y,LL z)
{
LL ans=1;
while(y)
{
if(y%2) ans=ans*x%z;
x=x*x%z;
y=y/2;
}
return ans;
}
LL phi(LL n) //求欧拉函数
{
LL ans=n;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
ans=ans-ans/i;
while(n%i==0)
n=n/i;
}
}
if(n>1) ans=ans-ans/n;
return ans;
}
int main()
{
cin>>a>>b>>c;
int len=strlen(b);
LL p=phi(c);
LL ans=0;
for(int i=0;i<len;i++)
ans=(ans*10+b[i]-'0')%p;
ans=ans+p;
cout<<quick_pow(a,ans,c)<<endl;
//system("pause");
return 0;
}
经典扩展
(洛谷)P4139 上帝与集合的正确用法
题目传送门:
题目大意:
首先我们可以根据扩展欧拉定理:
得到:
很显然这是一个递归的式子,边界条件为p=1,此时式子的值为0。而对于φ§,我们可以线性筛处理。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e7+10;
int n,tot,p[N],phi[N];
bool flag[N];
void pre()
{
phi[1]=1;
for(int i=2;i<N;i++)
{
if(!flag[i])
{
p[++tot]=i;
phi[i]=i-1;
}
for(int j=1;j<=tot&&i*p[j]<N;j++)
{
flag[i*p[j]]=1;
if(i%p[j]==0)
{
phi[i*p[j]]=phi[i]*p[j];
break;
}
else
phi[i*p[j]]=phi[i]*phi[p[j]];
}
}
}
LL quick_pow(LL x,LL y,LL mod)
{
LL ans=1;
while(y)
{
if(y%2) ans=ans*x%mod;
x=x*x%mod;
y=y/2;
}
return ans;
}
LL solve(int p)
{
if(p==1) return 0;
return quick_pow(2,solve(phi[p])+phi[p],p);
}
int main()
{
pre();
int t;
scanf("%d",&t);
while(t--)
{
int p;
scanf("%d",&p);
printf("%lld\n",solve(p));
}
//system("pause");
return 0;
}