洛谷-3871 GCDEX - GCD Extreme

题目描述
给出n,求所有gcd(i,j)之和,其中1<=i<j<=n. 不超过20000组数据,n<=1000000.
输入格式
The input file contains at most 20000 lines of inputs. Each line contains an integer N (1 < N < 1000001). The meaning of N is given in the problem statement. Input is terminated by a line containing a single zero.
输出格式
For each line of input produce one line of output. This line contains the value of G for the corresponding N. The value of G will fit in a 64-bit signed integer.

输入输出样例
输入 #1 复制
10
100
200000
0

输出 #1 复制
67
13015
143295493160

不同数据范围不同算法,这里只有n,那么
g ( n ) = ∑ i = 1 n − 1 g c d ( i , n ) g(n)=\sum_{i=1}^{n-1}{\rm gcd}(i,n) g(n)=i=1n1gcd(i,n)
那么答案就是:
∑ i = 1 n g ( n ) \sum_{i=1}^{n}g(n) i=1ng(n)
现在我们逐步化简:
g ( n ) = ∑ i = 1 n − 1 g c d ( i , n ) = ∑ d ∣ n d × ∑ i = 1 n − 1 [ g c d ( i , n ) = d ] = ∑ d ∣ n d × ∑ i = 1 n d − 1 [ g c d ( i , n d ) = 1 ] = ∑ d ∣ n d × φ ( n d ) \begin{aligned}g(n)&amp;=\sum_{i=1}^{n-1}{\rm gcd}(i,n)\\&amp;=\sum_{d|n}d\times\sum_{i=1}^{n-1}[{\rm gcd}(i,n)=d]\\&amp;=\sum_{d|n}d\times\sum_{i=1}^{\frac{n}{d}-1}[{\rm gcd}(i,\frac{n}{d})=1]\\&amp;=\sum_{d|n}d\times\varphi\left(\frac{n}{d}\right)\end{aligned} g(n)=i=1n1gcd(i,n)=dnd×i=1n1[gcd(i,n)=d]=dnd×i=1dn1[gcd(i,dn)=1]=dnd×φ(dn)
再埃氏筛一下就好了

#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cstdio>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<cmath>
#include<map>
#include<set>
using namespace std;
const int inf=0x7fffffff;
const double eps=1e-10;
const double pi=acos(-1.0);
inline int read(){
    int x=0,f=1;char ch;ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-') f=0;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch&15);ch=getchar();}
    if(f)return x;else return -x;
}
const int N=1000010; 
bool vis[N];
long long prim[N],phi[N],ans[N];
void get_phi(int n){
	phi[1]=0;
  	for(int i=2;i<=n;i++){
    	if(!vis[i]){phi[i]=i-1;prim[++prim[0]]=i;}
    	for(int j=1;j<=prim[0]&&i*prim[j]<=n;j++){
      		vis[i*prim[j]]=1;
      		if(i%prim[j]==0){phi[i*prim[j]]=phi[i]*prim[j];break;}
      		else phi[i*prim[j]]=phi[i]*(prim[j]-1);
    	}
  	}
	for(int i=1;i<=n;i++)ans[i]=phi[i];
	for(int i=2;i*i<=n;i++){
		ans[i*i]+=phi[i]*i;
    	for(int j=i+1;j*i<=n;j++)
    		ans[j*i]+=phi[i]*j+phi[j]*i;
  	}
	ans[1]=0;
	for(int i=2;i<=n;i++)ans[i]+=ans[i-1];
}
int n;
int main(){
	get_phi(1000000);
	while(scanf("%d",&n)==1&&n){printf("%lld\n",ans[n]);}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值