UESTC621 吴神的大脑

Problem Description
Given the value of N, you will have to find the value of G. 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 20000 lines of inputs. Each line contains an integer N (1<N <1000001). 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


即求n以内任意两数的最大公约数之和,试下可以发现,n增大只增加n与小于n的数的最大公约数,由此想到对每个n进行求解;

但是可以发现求解仍然非常困难,故换个角度,从约数的角度去考虑。对于 i 任意他的倍数与它均会有大于等于 i 的最大公约数,

我们可以发现,对于 i 的倍数 n ,比他小的数 a 可能有含有 i 这一约数, 但也有可能与 n 同时存在 另一个约数, 如 i=2,n=12 ,

a=6。我们只需先求出 n 以下 与 n 最大公约数 为 i 的数的个数即可,即为 euler[n/i]。(可以思考下为什么)

枚举所有的 i 即可。 

#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define LL long long
#define maxn 4000005
LL e[maxn],g[maxn],euler[maxn];

void euler_init(){
    int i,j;
    euler[1]=1;
    for(i=2;i<maxn;i++)
      euler[i]=i;
    for(i=2;i<maxn;i++)
       if(euler[i]==i)
          for(j=i;j<maxn;j+=i)
            euler[j]=euler[j]/i*(i-1);
}

void p(){
    int i,j;
    for(i=1;i<maxn;i++){
        e[i]=i-1;
    }
    for(i=2;i<maxn;i++){
        for(j=i+i;j<maxn;j+=i){
            e[j]+=euler[j/i]*(i-1);
        }
    }
    g[2]=e[2];
    for(int i=3;i<maxn;i++){
        g[i]=e[i]+g[i-1];
    }
}
int main()
{
    int n;
    euler_init();
    p();
    while(~scanf("%d",&n),n){
        printf("%lld\n",g[n]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值