# POJ 2480 Longge's problem 欧拉函数

914人阅读 评论(0)

f(M) = ∑d1 * φ(M / d1), d1 | M
f(N) = ∑d2 * φ(N / d2), d2 | N

f(MN) = ∑d * φ(MN / d), d | MN

f(MN)中的项与f(M) * f(N)中的项一一对应

#include<cstdio>
#include<cstring>
using namespace std;

#define MAXN 200000
#define lint __int64
struct Factor { lint b, e; };
Factor f[MAXN]; lint fnum;
lint a[MAXN], p[MAXN], pn;
lint n, ret;

void Prime()
{
lint i, j; pn = 0;
memset(a,0,sizeof(a));
for ( i = 2; i < MAXN; i++ )
{
if ( a[i] == 0 ) p[pn++] = i;
for ( j = 0; j < pn && i*p[j] < MAXN && (p[j]<=a[i] || !a[i]); j++ )
a[i*p[j]] = p[j];
}
}

lint Euler ( lint n )
{
lint ret = n;
for ( int i = 0; p[i] * p[i] <= n; i++ )
{
if ( n % p[i] == 0 )
{
ret = ret - ret / p[i];
while ( n % p[i] == 0 ) n /= p[i];
}
}
if ( n > 1 )
ret = ret - ret / n;
return ret;
}

void split ( lint n )
{
fnum = 0;
for ( int i = 0; p[i] * p[i] <= n; i++ )
{
if ( n % p[i] ) continue;
f[fnum].b = p[i]; f[fnum].e = 0;
while ( n % p[i] == 0 )
{
f[fnum].e++;
n /= p[i];
}
fnum++;
}
if ( n > 1 )
f[fnum].b = n, f[fnum++].e = 1;

}

void DFS ( lint val, int index ) //求n的每一个约数，然后利用欧拉函数
{
if ( index == fnum )
{
ret += Euler(n/val) * val;   //Euler(n/val)的值表示1-n中gcd(n,i）= val的个数
return;
}
for ( lint i = 0, tmp = 1; i <= f[index].e; i++, tmp *= f[index].b )
DFS ( val*tmp, index+1 );
}

int main()
{
Prime();
while ( scanf("%I64d",&n) != EOF )
{
split ( n );
ret = 0;
DFS ( 1, 0 );
printf("%I64d\n",ret);
}
}


#include<cstdio>
#include<cstring>
using namespace std;

#define MAXN 200000
#define lint __int64
struct Factor { lint b, e, mult; };
Factor f[MAXN]; lint fnum;
lint a[MAXN], p[MAXN], pn;

void Prime()
{
lint i, j; pn = 0;
memset(a,0,sizeof(a));
for ( i = 2; i < MAXN; i++ )
{
if ( a[i] == 0 ) p[pn++] = i;
for ( j = 0; j < pn && i*p[j] < MAXN && (p[j]<=a[i] || !a[i]); j++ )
a[i*p[j]] = p[j];
}
}

lint Euler ( lint n )
{
lint ret = n;
for ( int i = 0; p[i] * p[i] <= n; i++ )
{
if ( n % p[i] == 0 )
{
ret = ret - ret / p[i];
while ( n % p[i] == 0 ) n /= p[i];
}
}
if ( n > 1 )
ret = ret - ret / n;
return ret;
}

void split ( lint n )
{
fnum = 0;
for ( int i = 0; p[i] * p[i] <= n; i++ )
{
if ( n % p[i] ) continue;
f[fnum].b = p[i]; f[fnum].e = 0;
f[fnum].mult = 1;
while ( n % p[i] == 0 )
{
f[fnum].e++;
f[fnum].mult *= p[i];
n /= p[i];
}
fnum++;
}
if ( n > 1 )
f[fnum].b = f[fnum].mult = n, f[fnum++].e = 1;

}

int main()
{
Prime(); lint n;
while ( scanf("%I64d",&n) != EOF )
{
split ( n );
lint ret = 1, tmp, sum;
for ( int i = 0; i < fnum; i++ )
{
tmp = 1, sum = Euler(f[i].mult); //所有与f[i].mult互素的数先加起来
for ( int j = 1; j <= f[i].e; j++ )
{
tmp *= f[i].b;
sum += Euler(f[i].mult/tmp) * tmp;
}
ret *= sum;
}
printf("%I64d\n",ret);
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：479713次
• 积分：8126
• 等级：
• 排名：第2466名
• 原创：342篇
• 转载：49篇
• 译文：0篇
• 评论：34条
评论排行
最新评论