GCD Extreme
Accept: 124 Submit: 249
Time Limit: 1000 mSec Memory Limit : 32768 KB
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
Source
Contest for 2010 lecture II
题目大意:求题面程序段的值
题目分析:先看两个数据和时限,在Uva上本题100组数据,n为4e6,时限10s,Fzu上20000组数据,n为1e6,时限1s,先说复杂度高的莫比乌斯反演的做法,对于每个输入的n,枚举最大公约数然后利用反演容斥,复杂度O(Case * nlogn),在Uva上3s+跑完
#include <cstdio>
#define ll long long
int const MAX = 4e6 + 5;
int mob[MAX], p[MAX], sum[MAX];
bool noprime[MAX];
void Mobius()
{
int pnum = 0;
mob[1] = 1;
for(int i = 2; i < MAX; i++)
{
if(!noprime[i])
{
p[pnum ++] = i;
mob[i] = -1;
}
for(int j = 0; j < pnum && i * p[j] < MAX; j++)
{
noprime[i * p[j]] = true;
if(i % p[j] == 0)
{
mob[i * p[j]] = 0;
break;
}
mob[i * p[j]] = -mob[i];
}
}
}
int main()
{
Mobius();
int n;
while(scanf("%d", &n) != EOF && n)
{
ll ans = 0;
for(int i = 1; i <= n; i++)
{
for(int j = i; j <= n; j += i)
ans += (ll)i * (n / j) * (n / j) * mob[j / i];
ans -= (ll) i;
}
printf("%lld\n", ans / 2);
}
}
FZU上这种做法肯定超时,回到题目,因为有∑gcd(i, N) = ∑(d|N) d*phi[N/d],则G(N) = ∑gcd(1, N) + ∑gcd(2, N) + ... + ∑gcd(N-1, N)
令f[i] = ∑gcd(i, N),则G(N) = ∑f[i],只需要筛出f[i],求前缀和预处理然后就能O(1)查询,复杂度为O(MAX*logMAX),100ms+,FZU上的long long要用I64d
#include <cstdio>
#define ll long long
int const MAX = 1000005;
int p[MAX], phi[MAX], f[MAX], n;
ll ans[MAX];
bool noprime[MAX];
void pre()
{
int pnum = 0;
for(int i = 2; i < MAX; i++)
{
if(!noprime[i])
{
p[pnum ++] = i;
phi[i] = i - 1;
}
for(int j = 0; j < pnum && i * p[j] < MAX; j++)
{
noprime[i * p[j]] = true;
if(i % p[j] == 0)
{
phi[i * p[j]] = phi[i] * p[j];
break;
}
phi[i * p[j]] = phi[i] * (p[j] - 1);
}
}
for(int i = 1; i < MAX; i++)
{
for(int j = i; j < MAX; j += i)
f[j] += (ll)i * phi[j / i];
ans[i] = ans[i - 1] + f[i];
}
}
int main()
{
pre();
while(scanf("%d", &n) != EOF && n)
printf("%I64d\n", ans[n]);
}