您的位置:首页 > 产品设计 > UI/UE

UESTC621 吴神的大脑

2016-07-13 14:38 288 查看
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
);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: