您的位置:首页 > 其它

找新朋友

2015-08-04 17:06 344 查看

找新朋友

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 9201 Accepted Submission(s): 4856



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

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

[align=left]Output[/align]
对于每一个N,输出一行新朋友的人数,这样共有CN行输出。

[align=left]Sample Input[/align]

2
25608
24027


[align=left]Sample Output[/align]

7680
16016我的超时了~
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int main()
{
int T,n,i,count;
cin>>T;
while(T--)
{
count=0;
cin>>n;
for(i=2;i<n;i++)
{
if(gcd(i,n)>1)
count++;
}
cout<<(n-count-1)<<endl;
}
return 0;
}
[code]看了一个大神的博客,感觉写的很好。
http://www.cnblogs.com/chuanlong/archive/2012/10/18/2728893.html
<pre name="code" class="cpp">#include <stdio.h>
#include <string>
#define MAXN 32768
int a[MAXN + 5];
int main()
{
int i, j, k, CN, num, count;
scanf("%d", &CN);
while (CN--)
{
//initialize the array
memset(a, 0, sizeof(a));
scanf("%d", &num);
//if the number have common divisor with the input, make the value = 1
for (j = 2; j < num; j++)
if (num % j == 0)
for (k = j; k < num; k += j)
a[k] = 1;
count = 0;
//numbers of zero is numbers of new friends, pay attention to k = 1
for (k = 1; k < num; k++)
if (a[k] == 0)
count++;
printf("%d\n", count);
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: