# 题目链接

https://lydsy.com/JudgeOnline/problem.php?id=2005

# 题解

\begin{aligned} & \sum_{i=1}^n \sum_{j=1}^m (2\gcd(i,j)-1)\\ = & 2\sum_{i=1}^n \sum_{j=1}^m \gcd(i,j)-nm \end{aligned}

\begin{aligned} g = & \sum_{i=1}^n\sum_{j=1}^m \gcd(i,j)\\ = & \sum_{T=1}^{\min(n,m)}\lfloor \frac{n}{T} \rfloor \lfloor\frac{m}{T}\rfloor \sum_{d|T}d\mu(\frac{d}{T})\\ = & \sum_{T=1}^{\min(n,m)}\lfloor\frac{n}{T}\rfloor \lfloor\frac{m}{T}\rfloor\varphi(T) \end{aligned}

\begin{aligned} & 2g+nm\\ = & 2\sum_{T=1}^{\min(n,m)}\lfloor\frac{n}{T}\rfloor\lfloor\frac{m}{T}\rfloor\varphi(T)+nm \end{aligned}

# 代码

#include <cstdio>
#include <algorithm>

{
int x=0,f=1;
char ch=getchar();
while((ch<'0')||(ch>'9'))
{
if(ch=='-')
{
f=-f;
}
ch=getchar();
}
while((ch>='0')&&(ch<='9'))
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}

const int maxn=100000;

int p[maxn+10],prime[maxn+10],cnt,phi[maxn+10];

int getprime()
{
p[1]=1;
phi[1]=1;
for(int i=2; i<=maxn; ++i)
{
if(!p[i])
{
prime[++cnt]=i;
phi[i]=i-1;
}
for(int j=1; (j<=cnt)&&(i*prime[j]<=maxn); ++j)
{
p[i*prime[j]]=1;
if(i%prime[j]==0)
{
phi[i*prime[j]]=phi[i]*prime[j];
break;
}
phi[i*prime[j]]=phi[i]*(prime[j]-1);
}
}
return 0;
}

int n,m;
long long ans;

int main()
{
getprime();
for(int i=1; i<=std::min(n,m); ++i)
{
ans+=1ll*(n/i)*(m/i)*phi[i];
}
printf("%lld\n",2*ans-1ll*n*m);
return 0;
}



©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客