POJ2480 Longge's problem

题意

Language:
Longge's problem
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 10642Accepted: 3563

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

Source

POJ Contest,Author:Mathematica@ZSU

分析

\[\sum_{i=1}^n\gcd(i,n) \\ =\sum_{d|n}d*\sum_{i=1}^{\frac nd}[\gcd(i,\frac nd)=1]=\sum_{d|n}d*\varphi(\frac nd) \\ =\sum_{d|n}d*\frac nd *\prod_{i=1,p_i|\frac nd}^m(1-\frac 1p_i) \]

那么直接把\(n\)质因数分解就行了。时间复杂度\(O(\sqrt{n})\)

#include<iostream>
typedef long long ll;
int main(){
	ll n;
	while(~scanf("%lld",&n)){
		ll ans=n;
		for(ll i=2,cnt;i*i<=n;++i)if(n%i==0){
			cnt=0;
			while(n%i==0) n/=i,++cnt;
			ans=ans/i*((i-1)*cnt+i);
		}
		if(n>1) ans=ans/n*((n-1)+n);
		printf("%lld\n",ans);
	}
	return 0;
}

posted on 2019-04-03 15:06  autoint  阅读(80)  评论(0编辑  收藏  举报

导航