题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=4335
题目意思:
给你三个数b,p,m
问你满足0<=n<=m 且n^n!%p==b的n有多少个
解题思路:
主要考察
a^x % c = a^(x % phi(c) + phi(c)) %c 其中x>= phi(c)
phi(c)为欧拉函数
第一部分 n! < phi(c) 这时就需要直接计算n! ,好在phi(c)不会很大。
第二部分 n! >= phi(c) 但是 n! % phi(c) != 0 这一部分同样需要暴力计算,不过可以进行取模运算了,不会出现非常大的数
第三部分n! >= phi(c) 并且n! % phi(c) == 0 这一部分就转化为了 n^phi(c) % c 然后就变成了(n % c) ^ phi(c) % c 那么就成了一个长度为c的循环节了
具体见代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define ULL unsigned long long
//打表求欧拉函数
const int maxp = 100000+20;
ULL phi[maxp];
void phi_table()
{
memset(phi,0,sizeof(phi));
phi[1] = 1;
for(int i=2;i<maxp;i++)
{
if(!phi[i])
{
for(int j=i;j<maxp;j+=i)
{
if(!phi[j])
phi[j]=j;
phi[j] = phi[j]/i*(i-1);
}
}
}
}
ULL euler_phi(ULL p)
{
ULL m = (ULL)sqrt(p+0.5);
ULL ans = p;
for(ULL i=2;i<=m;i++)
{
if(p%i==0)
{
ans = ans/i*(i-1);
while(p%i==0)
p/=i;
}
}
if(p>1)
ans = ans/p*(p-1);
return ans;
}
ULL power(ULL a,ULL x,ULL p)
{
ULL ret = 1;
a = a%p;
while(x>0)
{
if(x&1)
ret = ret*a%p;
a = a*a%p;
x = x/2;
}
return ret;
}
int main()
{
//phi_table();
int T;
int ca=1;
scanf("%d",&T);
while(T--)
{
ULL b,p,m;
cin>>b>>p>>m;
//这种情况的结果会超过ULL的范围,所以要特判
if(b==0 && p==1 && m==18446744073709551615ULL)
{
printf("Case #%d: 18446744073709551616\n",ca++);
continue;
}
ULL _phi = euler_phi(p);
ULL ans = 0;
if(b==0)
ans++;
ULL sum=1;
//先看n!%phi!=0的,当n!<phi时,MOD之后肯定不为0
for(ULL i=1;i<_phi&&i<=m;i++)
{
sum = sum*i%_phi+_phi;
if(power(i,sum,p) == b)
ans++;
}
//然后再从phi到m,但是我们注意到后面n!%phi==0,则方程就是i^phi%p==b
//则(i+kp)^phi%p==b,则看从i开始到m之间隔了几个p的长度
for(ULL i=_phi;i<_phi+p&&i<=m;i++)
{
if(power(i,_phi,p)==b)
{
ans+=(m-i)/p+1;
}
}
cout<<"Case #"<<ca++<<": "<<ans<<endl;
}
return 0;
}