poj 2480 Longge's problem 积性函数性质+欧拉函数 ʕ •ᴥ•ʔ

Longge's problem

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 7343   Accepted: 2422

Description

Longge is good at mathematics and he likes to think about hard mathematical problems which will be solved by some graceful algorithms. Now a problem comes: Given an integer N(1 < N < 2^31),you are to calculate ∑gcd(i, N) 1<=i <=N. 

"Oh, I know, I know!" Longge shouts! But do you know? Please solve it. 

Input

Input contain several test case. 
A number N per line. 

Output

For each N, output ,∑gcd(i, N) 1<=i <=N, a line

Sample Input

2
6

Sample Output

3
15

题目意思很简单:给一个n,求所有的gcd(i,n)之和,其中1<= i <= n.

设p是n的一个约数,则会存在一些i,使得gcd(i,n)=p -->gcd(i/p , n/p) = 1,即i/p和n/p互素,那么一共有几个满足条件的i呢,phi(n/p)个!!且有几个这个的i就有几个p,所以结果就是p*phi(n/p),然后对n的所有约数pi都求出来然后求和就是本题的答案,即答案是:f(n)=sum(p*phi(n/p)) ,p为n的因子。

比如12有因子2的时候,也会有因子6,这个时候因子2的个数有phi[12/2],因子6的个数有phi[12/(12/2)]

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
ll lala(ll n)
{
	ll res=n;
	for(ll i=2;i*i<=n;i++)
	{
		if(n%i==0)
		{
			res=res/i*(i-1);
			while(n%i==0)
			{
				n/=i;
			}
		}
	}
	if(n>1)
	res=res/n*(n-1);
	return res;
}
int main()
{
	ll n;
	while(scanf("%lld",&n)!=EOF)
	{
		ll ans=0;
		for(ll i=1;i*i<=n;i++)
		{
			if(n%i==0)
			{
				ans+=i*lala(n/i);
				if(i*i!=n)
				//i*i != n时候ans+= i*phi(N/i) + N/i*phi(i)
				//相等时候 只加一个 因为这时候i和N/i相等
				{
					ans+=n/i*lala(i);

				}
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/henucm/article/details/81606663