Find the sum of the greatest common divisor 51nod 1040

The meaning of the question:
Given an n, find the sum of n numbers 1-n, the greatest common divisor of the same n. For example: n = 6
1,2,3,4,5,6 The greatest common divisor of 6 is 1,2,3,2,1,6 respectively, added together = 15

Input
1 number N(N <= 10^9)
Output Sum
of common divisors
Input example
6
Output example
15

/*
(欧拉函数)

给你n,然后求[1,n]所有数与n的最大公约数的和
如果直接暴力 看下数据不用想肯定超时

n的最大公约数必定是n的因子v,所以考虑枚举因子分别求他们的个数num,那么因子v对答案的贡献就是v*num
相当于求[1,n]中 GCD(a[i],n) = v的个数,也就成了GCD(a[i]/v,n/v)=1的个数。 欧拉函数求出即可。

欧拉函数:[1,n]中 gcd[i,n]=x的个数
这个题只能直接求欧拉函数 如果打表的话这个题目会炸

*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>

using namespace std;

#define LL long long

LL eluar(LL n)//欧拉函数 直接求解
{
    LL ans=1;
    for(LL i=2; i*i<=n; i++)
    {
        if(n%i==0)
        {
            n/=i;
            ans*=i-1;
            while(n%i==0)
            {
                n/=i;
                ans*=i;
            }
        }
    }
    if(n>1)
        ans*=n-1;
    return ans;
}

int main()
{
    LL n;
    while(~scanf("%lld",&n))
    {
        LL ans=0;
        for(LL i=1; i*i<=n; i++)
        {
            if(n%i==0)
            {
                LL t=n/i;
                ans+=i*eluar(t);
                if(i!=t)
                {
                    ans+=t*eluar(n/t);
                }
            }
        }
        printf("%lld\n",ans);


    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324479771&siteId=291194637