恒邪

[ACM] hdu 1286 找新朋友(欧拉函数)

找新朋友

Time Limit: 2000/1000 MS(Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s):6928    Accepted Submission(s): 3593


Problem Description

 

新年快到了,“猪头帮协会”准备搞一个聚会,已经知道现有会员N人,把会员从1到N编号,其中会长的号码是N号,凡是和会长是老朋友的,那么该会员的号码肯定和N有大于1的公约数,否则都是新朋友,现在会长想知道究竟有几个新朋友?请你编程序帮会长计算出来。

 


 

Input

 

第一行是测试数据的组数CN(Casenumber,1<CN<10000),接着有CN行正整数N(1<n<32768),表示会员人数。

 


 

Output

 

对于每一个N,输出一行新朋友的人数,这样共有CN行输出。

 


 

Sample Input

 

2

25608

24027

 


 

Sample Output

 

7680

16016

 


 

Author

 

SmallBeer(CML)

 


 

Source

 

杭电ACM集训队训练赛(VII

 

题解:

数论,对正整数n欧拉函数是少于或等于n的数中与n互质的数的数目。

φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),其中p1, p2……pnx的所有质因数,x是不为0的整数。φ(1)=1

代码:

方法一:求单个phi(n)是多少

#include <iostream>

#include <cmath>

using namespace std;

 

const int maxn=32768;

 

int phi(int n)//求phi(n)

{

    int m=(int)sqrt(n+0.5);

    int ans=n;

    for(int i=2;i<=m;i++)

        if(n%i==0)

    {

        ans=ans/i*(i-1);

        while(n%i==0)

            n/=i;

    }

    if(n>1)

        ans=ans/n*(n-1);

    return ans;

}

 

int main()

{

    int c;cin>>c;

    int n;

    while(c--)

    {

        cin>>n;

        cout<<phi(n)<<endl;

    }

    return 0;

}


方法二:求出欧拉函数表

代码:

#include <iostream>

using namespace std;

 

const int maxn=32768;

int phi[maxn];

 

void phi_table(int n)

{

    for(int i=2;i<=n;i++)

        phi[i]=0;

    phi[1]=1;

    for(int i=2;i<=n;i++)

        if(!phi[i])

        for(int j=i;j<=n;j+=i)

    {

        if(!phi[j])

            phi[j]=j;

        phi[j]=phi[j]/i*(i-1);

    }

}

 

int main()

{

    phi_table(maxn);

    int c;cin>>c;

    int n;

    while(c--)

    {

        cin>>n;

        cout<<phi[n]<<endl;

    }

    return 0;

}


 

 

posted on 2014-04-02 20:39  恒邪  阅读(160)  评论(0编辑  收藏  举报

导航