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

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-8
using 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;}
//head
ll 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值