POJ 2480 Longge's problem (欧拉函数)

来源:互联网 发布:董小飒淘宝店赚钱吗 编辑:程序博客网 时间:2024/05/17 06:52

Longge’s problem
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8107 Accepted: 2680

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的范围可知暴力枚举肯定是不行的了,我们可以通过N的约数来求出gcd和,通过枚举N的约数的欧拉函数值及其商的欧拉函数值相乘求出,注意当N可以开方的时候,减去重复运算的次数,复杂度为O(N).

ac代码:

#include<stdio.h>#include<math.h>#include<string.h>#include<stack>#include<set>#include<map>#include<queue>#include<vector>#include<iostream>#include<algorithm>#define MAXN 1010000#define LL long long#define ll __int64#define INF 0x7fffffff#define mem(x) memset(x,0,sizeof(x))#define PI acos(-1)#define eps 1e-8using namespace std;ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}ll lcm(ll a,ll b){return a/gcd(a,b)*b;}ll powmod(ll a,ll b,ll MOD){ll ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}double dpow(double a,ll b){double ans=1.0;while(b){if(b%2)ans=ans*a;a=a*a;b/=2;}return ans;}//headll eular(ll n){    ll ret=1,i;    for(i=2;i*i<=n;i++)    {        if(n%i==0)        {            n/=i,ret*=i-1;            while(n%i==0)            n/=i,ret*=i;        }    }    if(n>1)    ret*=n-1;    return ret;}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        ll ans=0;        for(int i=1;i<=(int)sqrt(n*1.0);i++)        {            if(n%i==0)            {                ans+=n/i*eular(i);                if(i*i!=n)                ans+=i*eular(n/i);            }        }        printf("%I64d\n",ans);    }    return 0;}
0 0
原创粉丝点击