GuGuFishtionTime Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1325 Accepted Submission(s): 516 Problem Description Today XianYu is too busy with his homework, but the boring GuGu is still disturbing him!!!!!!At the break time, an evil idea arises in XianYu's mind. ‘Come on, you xxxxxxx little guy.’ ‘I will give you a function ϕ(x) which counts the positive integers up to x that are relatively prime to x .’ ‘And now I give you a fishtion, which named GuGu Fishtion, in memory of a great guy named XianYu and a disturbing and pitiful guy GuGu who will be cooked without solving my problem in 5 hours.’ ‘The given fishtion is defined as follow: Gu(a,b)=ϕ(ab)ϕ(a)ϕ(b) And now you, the xxxxxxx little guy, have to solve the problem below given m ,n ,p .’ (∑a=1m∑b=1nGu(a,b))(modp) So SMART and KINDHEARTED you are, so could you please help GuGu to solve this problem? ‘GU GU!’ GuGu thanks.
Input Input contains an integer T indicating the number of cases, followed by T lines. Each line contains three integers m ,n ,p as described above.
Output Please output exactly T lines and each line contains only one integer representing the answer.
Sample Input 1 5 7 23
Sample Output 2 |
贴一下官方题解:
其实最重要的就是推导出原式等价于gcd(a,b)/Φ(gcd(a,b)),因为欧拉函数Φ(n)=∏(pi-1)(pi^(ai-1)),那么假设a和b有一个共同的质因数p。
那么对于Φ(ab)来说,这一项是
对于Φ(a)Φ(b)来说,这一项是
所以Φ(ab)/Φ(a)Φ(b)中考虑质因数p这一项的话就为p/(p-1),另外我们再看如果质因数p只在a或b中出现的话约分后都为1,所以只有同时在a和b中出现才会产生贡献。又因为,就能由原式推导出gcd(a,b)/Φ(gcd(a,b))。然后就如官方题解那样将问题简化了,莫比乌斯反演即可,预处理逆元和欧拉函数。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+5;
int m,n,p,t;
int mu[maxn],vis[maxn],phi[maxn],inv[maxn];
int prime[maxn];
void eulur()
{
for(int i=2;i<maxn;i++)
phi[i]=0;
phi[1]=1;
for(int i=2;i<maxn;i++)
{
if(!phi[i])
{
for(int j=i;j<maxn;j+=i)
{
if(!phi[j]) phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
}
}
void mobius()
{
memset(prime,0,sizeof(prime));
memset(mu,0,sizeof(mu));
memset(vis,0,sizeof(vis));
mu[1]=1;
int cnt=0;
for(int i=2;i<maxn;i++)
{
if(!vis[i])
{
prime[cnt++]=i;
mu[i]=-1;
}
for(int j=0;j<cnt&&i*prime[j]<maxn;j++)
{
vis[i*prime[j]]=1;
if(i%prime[j]) mu[i*prime[j]]=-mu[i];
else
{
mu[i*prime[j]]=0;
break;
}
}
}
}
void init()
{
inv[1]=1;
for(int i=2;i<maxn;i++)
{
inv[i]=inv[p%i]*(ll)(p-p/i)%p;
}
}
ll cal(int b,int d,int k)
{
ll ans=0;
b/=k,d/=k;
if(b>d) swap(b,d);
for(int i=1;i<=b;i++)
ans+=1LL*mu[i]*(b/i)*(d/i);
return ans;
}
int main()
{
eulur();
mobius();
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&p);
ll ans=0;
init();
for(int k=1;k<=min(n,m);k++)
{
ll temp=cal(n,m,k)%p;
temp=temp*k%p*inv[phi[k]]%p;
ans=(ans+temp)%p;
}
printf("%lld\n",ans);
}
return 0;
}