BZOJ2705[SDOI2012]Longge的问题——欧拉函数

Description
Longge的数学成绩非常好,并且他非常乐于挑战高难度的数学问题。现在问题来了:给定一个整数N,你需要求出∑gcd(i, N)(1<=i <=N)。
Input
一个整数,为N。
Output
一个整数,为所求的答案。
Sample Input
6
Sample Output
15
HINT
【数据范围】
对于60%的数据,0< N<=2^16。
对于100%的数据,0< N<=2^32。


这道题要求的是 i = 1 n g c d ( i , n ) 我们可以这么考虑,首先与n互质的数,他们贡献的gcd是1,所以对答案的贡献就是 p h i ( n ) 1 ,而对于与(n/i)互质的数,他们对答案的贡献就是 p h i ( n / i ) i (因为这些互质的数x对应的实际的数是x*i),所以最终答案的表达式就是:(如果n有m个因数,每个因数是f[i])

a n s = i = 1 m p h i ( f [ i ] ) ( n / f [ i ] )

由于这道题的范围很大,所以我们可以用phi的展开公式来求,详见这篇博客的性质4
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){
    char c;ll x;while(c=getchar(),c<'0'||c>'9');x=c-'0';
    while(c=getchar(),c>='0'&&c<='9') x=x*10+c-'0';return x;
}
ll n,ans;
ll getphi(ll x){
    ll res=x,p=sqrt(x);
    register ll i;
    for(i=2;i<=p;i++){
        if(x%i!=0) continue;
        res-=res/i;while(x%i==0) x/=i;
    }
    if(x>1) res-=res/x;
    return res;
}
int main()
{
    n=read();
    register ll i;
    for(i=1;i*i<=n;i++){
        if(n%i!=0) continue;
        ans+=getphi(i)*(n/i),ans+=getphi(n/i)*i;
        if(i*i==n) ans-=getphi(i)*i;
    }
    printf("%lld",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/stevensonson/article/details/80530057
今日推荐