POJ 2048 Longge's problem

题意:∑gcd(i, N) 1<=i <=N

思路:结论是∑gcd(i, N) = ∑(d|N) d*phi[N/d]phi[N / d]就是1 - N中与N最大公约数为d的个数,因为phi[n]表示小于等于n且与n互质的数的个数,那么n除去d这个因子后所求的欧拉函数值正是乘了d以后与N最大公约数为d的数的个数所以直接用公式即

#include<iostream>
#include<cstdio>
#include<cstring>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N=105;
const int inf=0x3f3f3f3f;
typedef long long LL;
LL getphi(int x) {
    LL ans=x;
    for(LL i=2;i*i<=x;i++) {
       if(x%i==0) {
            ans-=ans/i;
            while(x%i==0) {
                x/=i;
            }
       }
    }
    if(x>1) {
        ans-=ans/x;
    }
    return ans;
}
int main() {
    LL n;
    while(scanf("%lld",&n) != EOF && n) {
        LL ans=0;
        for(LL i=1;i*i<=n;i++) {
            if(n%i==0) {
                ans+=i*getphi(n/i);
                if(i*i!=n) ans+=n/i*getphi(i);
            }
        }
        printf("%lld\n",ans);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41231363/article/details/80317187