suxxsfe

一言(ヒトコト)

P2303 [SDOI2012]Longge的问题

P2303 [SDOI2012]Longge的问题

\(\sum_{i=1}^n\gcd(i,n)\)


\(\gcd\)的问题往\(\varphi\)上想就对了
先来个套路变形:

\[\sum_{d|n}\sum_{i=1}^n d\cdot[\gcd(i,n)=d] \]

然后对中括号里的东西变一变,并提出\(d\)

\[\sum_{d|n}d\sum_{i=1}^n[\gcd(\frac{i}{d},\frac{n}{d})=1] \]

\(i\)替代\(\frac{i}{d}\)的同时要改变枚举上界

\[\sum_{d|n}d\sum_{i=1}^{\frac{n}{d}}[\gcd(i,\frac{n}{d})=1] \]

然后最里面就是\(\varphi\)

\[\sum_{d|n}d\cdot\varphi(\frac{n}{d}) \]

然后基本就结束了,用\(\varphi(x)=x\prod\dfrac{p_i-1}{p_i}\)这个式子\(O(\sqrt x)\)地求\(\varphi\)就行
总复杂度\(O(\text{因子个数}\times\sqrt n)\)

其实求\(\varphi\)有一种\(x^{\frac{1}{4}}\)的方法,但一般应该用不上
洛谷题解里神兔的方法也更优,但我不会

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstring>
#define reg register
#define EN std::puts("")
#define LL long long
inline LL read(){
	register LL x=0;register int y=1;
	register char c=std::getchar();
	while(c<'0'||c>'9'){if(c=='-') y=0;c=std::getchar();}
	while(c>='0'&&c<='9'){x=x*10+(c^48);c=std::getchar();}
	return y?x:-x;
}
inline LL phi(LL n){
	LL ret=n;
	for(reg LL i=2;i*i<=n;i++){
		if(!(n%i)) ret=ret/i*(i-1);
		while(!(n%i)) n/=i;
	}
	if(n>1) ret=ret/n*(n-1);
	return ret;
}
int main(){
	reg LL n=read(),i,ans=0;
	for(i=1;i*i<n;i++)if(!(n%i)){
		ans+=phi(i)*(n/i)+phi(n/i)*i;
	}
	if(i*i==n) ans+=phi(i)*i;
	std::printf("%lld",ans);
	return 0;
}
posted @ 2020-04-03 14:50  suxxsfe  阅读(119)  评论(0编辑  收藏  举报