HDU 1286.找新朋友【筛选法】【欧拉函数】【11月25】

来源:互联网 发布:法兰克机器人编程 编辑:程序博客网 时间:2024/05/22 15:08

找新朋友

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

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

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

Sample Input
22560824027
 

Sample Output
768016016
这题我用的筛选法,还可以用欧拉函数的方法。看代码吧:

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <cmath>#include <algorithm>using namespace std;int f[35000],cn,n,ans;int main(){    cin>>cn;    while(cn--)    {        ans=0;        memset(f,0,sizeof(f));        scanf("%d",&n);        for(int i=2;i<n;i++)        {            if(n%i==0&&f[i]==0)            {                for(int j=i;j<n;j+=i)//一定有公约数i,筛掉                    f[j]=1;            }        }        for(int i=1;i<n;i++)        {            if(!f[i]) ans++;        }        cout<<ans<<endl;    }    return 0;}


欧拉函数的方法如下:

#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<iostream>using namespace std;typedef long long LL;LL Eular( LL x ){    if( x == 0 ) return 0;    LL res = 1, t = x;    for(LL i = 2; i <= (LL)sqrt(1.*x); i++)    {        if( t%i == 0 )        {            res *= (i-1);            t /= i;            while( t%i ==0 )            {                res *= i;                t /= i;            }        }        if( t == 1 ) break;    }    if( t > 1 ) { res *= (t-1); }    return res;}int main(){    LL x;    int N;    scanf("%d", &N);    while(N--)    {        scanf("%lld", &x);        cout << Eular(x) << endl;    }    return 0;}

用时0MS。

0 0
原创粉丝点击