UVA 11424 UVA 11424 GCD - Extreme (I) (欧拉函数)

Given the value of N, you will have to find the value of G. The definition of G is given below: i< N j≤N
G= GCD(i,j) i=1 j=i+1
Here GCD(i,j) means the greatest common divisor of integer i and integer j.
For those who have trouble understanding summation notation, the meaning of G is given in the following code:
G=0;
for(i=1;i< N;i++)
for(j=i+1;j<=N;j++)
{
G+=gcd(i,j);
}
/*Here gcd() is a function that finds
the greatest common divisor of the two
input numbers*/
Input
The input file contains at most 100 lines of inputs. Each line contains an integer N (1 < N < 4000001). The meaning of N is given in the problem statement. Input is terminated by a line containing a single zero.
Output
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.
Sample Input
10
100
200000
0
Sample Output
67
13015
143295493160

解释来自:http://blog.csdn.net/u011639256/article/details/41382879

我们令f(n) = gcd(1, n) + gcd(2, n) + … + gcd(n-1, n)

则对应的结果s(n) = f(2) + f(3) + … + f(n)

所以s(n) = s(n-1)+f(n)

因此我们只需求出所有的f(n),在递推即可

取g(n, i)表示小于n且与n的gcd值等于i的数x的个数(gcd(n, x) = i)

则f(n) = 1*gcd(n, 1) + 2*gcd(n ,2) + …

而gcd(n, x) = i即gcd(n/i, x/i) = 1

所以g(n, i) == phi(n/i)

另外用线性筛预处理了欧拉函数的值。

#include "cstring"
#include "cstdio"
#include "string.h"
#include "iostream"
using namespace std;
#define Max 4000005
int euler[Max];
long long ans[Max];
void Init(){
    euler[1]=1;
    for(int i=2;i<Max;i++)
        euler[i]=i;
    for(int i=2;i<Max;i++)
        if(euler[i]==i)
            for(int j=i;j<Max;j+=i)
                euler[j]=euler[j]/i*(i-1);
}
long long f[Max],s[Max];
void gao()
{
    ans[1]=1;
    memset(ans,0,sizeof(ans));
    for(int i=1;i<Max;i++)
         for(int n=i*2;n<Max;n+=i)
             f[n]+=i*euler[n/i];
    s[2]=f[2];
    for(int n=3;n<Max;n++)
        s[n]=s[n-1]+f[n];
}
int main()
{
    int n;
    Init();
    gao();
    while(~scanf("%d",&n)&&n)
    {
        printf("%lld\n",s[n]);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值