UVa 11426 - GCD - Extreme (II) 转化+筛法生成欧拉函数表

《训练指南》p.125

设f[n] = gcd(1, n) + gcd(2, n) + …… + gcd(n - 1, n);

则所求答案为S[n] = f[2]+f[3]+……+f[n];

求出f[n]即可递推求得S[n]:S[n] = S[n - 1] + f[n];

所有gcd(x, n)的值都是n的约数,按照约数进行分类,令g(n, i)表示满足gcd(x, n) = i && x < n 的正整数x的个数,则f[n] = sum{ i * g(n, i) | n % i = 0 };

gcd( x, n ) = i 的充要条件为:gcd( x / i, n / i ) = 1; 因此满足条件的x/i有phi(n/i)个,说明g(n, i) = phi( n/i );

如果依次计算f[n],枚举f[n]的约数的话效率太低

因此对于每个i枚举它的倍数n并更新f[n],时间复杂度与素数筛法同阶。

 

#include <cstdio>

#include <cstring>

#include <cstdlib>

#include <algorithm>



#define LL long long int



using namespace std;



const int MAXN = 4000100;



LL phi[MAXN];

LL S[MAXN];

LL f[MAXN];



//筛法计算欧拉数

void phi_table( int n )

{

    for ( int i = 2; i < n; ++i ) phi[i] = 0;

    phi[1] = 1;

    for ( int i = 2; i < n; ++i )

        if ( !phi[i] )

        {

            for ( int j = i; j < n; j += i )

            {

                if ( !phi[j] )

                    phi[j] = j;

                phi[j] = phi[j] / i * (i - 1);

            }

        }

    return;

}



int main()

{

    phi_table( MAXN );



    memset( f, 0, sizeof(f) );

    for ( int i = 1; i < MAXN; ++i )

        for ( int j = i * 2; j < MAXN; j += i )

            f[j] += i * phi[j / i];



    S[2] = f[2];

    for ( int i = 3; i < MAXN; ++i )

        S[i] = S[ i - 1 ] + f[i];



    int n;

    while ( scanf( "%d", &n ), n )

    {

        printf("%lld\n", S[n] );

    }

    return 0;

}

 

你可能感兴趣的:(ext)