码迷,mamicode.com
首页 > 其他好文 > 详细

华为机考--亮着电灯的盏数

时间:2014-09-10 19:08:50      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   2014   div   

亮着电灯的盏数 
一条长廊里依次装有n(1 ≤ n ≤ 65535)盏电灯,从头到尾编号1、2、3、…n-1、n。每盏电灯由一个拉线开关控制。开始,电灯全部关着。
有n个学生从长廊穿过。第一个学生把号码凡是1的倍数的电灯的开关拉一下;接着第二个学生把号码凡是2的倍数的电灯的开关拉一下;接着第三个学生把号码凡是3的倍数的电灯的开关拉一下;如此继续下去,最后第n个学生把号码凡是n的倍数的电灯的开关拉一下。n个学生按此规定走完后,长廊里电灯有几盏亮着。
注:电灯数和学生数一致。

 

用C++实现:

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int n;
 7     bool light[100];
 8     int count;
 9     while(cin>>n)
10     {
11         count = 0;
12         int i,j;
13         for (i=1;i<=n;i++)
14         {
15             light[i]=false;
16         }
17         for (i=1;i<=n;i++)
18         {
19             for (j=1;j<=i;j++)
20             {
21                 if (i%j==0)
22                 {
23                     light[i]=!light[i];
24                 }
25             }
26         }
27         for (i=1;i<=n;i++)
28         {
29             if (light[i])
30             {
31                 count++;
32             }
33         }
34         cout<<count<<endl;
35     }
36     return 0;
37 }

运行结果:

bubuko.com,布布扣

华为机考--亮着电灯的盏数

标签:style   blog   http   color   os   io   for   2014   div   

原文地址:http://www.cnblogs.com/LiuYujie/p/3964916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!