您的位置:首页 > 其它

UVa11426 - GCD - Extreme (II)(欧拉函数的妙用)

2014-11-23 16:30 411 查看
Given the value of N, you willhave to find the value of G. The definition of G is given below:



 

Here GCD(i,j) means the greatest common divisor of integer i and integer j.

 

For those who have troubleunderstanding summation notation, the meaning of G is given in the followingcode:

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 100lines of inputs. Each line contains an integer N (1<N<4000001). Themeaning of N is given in the problem statement. Input is terminated by a linecontaining a single zero. 

 

Output

For each lineof input produce one line of output. This line contains the value of G for thecorresponding N. The value of G will fit in a 64-bit signed integer.

 

Sample Input                              Output for SampleInput

10

100

200000

0

 

67

13015

143295493160

 

题意:给出一个整数N,求出所有最大公约数的和
思路:欧拉函数

#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN = 4000001;

typedef long long LL;

int phi[MAXN];
LL ans[MAXN];

void init()
{
memset(ans, 0x00, sizeof(ans));
for (int i = 1; i < MAXN; i++) phi[i] = i;
for (int i = 2; i < MAXN; i++) {
if (phi[i] == i) {
for (int j = i; j < MAXN; j += i) {
phi[j] = phi[j] / i * (i - 1);
}
}

for (int j = 1; j * i < MAXN; j++) {
ans[j * i] += j * phi[i];
}
}

for (int i = 1; i < MAXN; i++) ans[i] += ans[i - 1];
}

int main()
{
#ifndef ONLINE_JUDGE
freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif

init();
int n;
while (scanf("%d", &n), n) {
printf("%lld\n", ans
);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: