第七章第二十三题(游戏:储物柜难题)(Game: locker problem)
-
**7.23(游戏:储物柜难题)一个学校有100个储物柜和100个学生。所有的储物柜在上学第一天都是关着的。随着学生进来,死一个学生(用S1表示)打开每个柜子。然后,第二个学生(用S2表示)懂第二个柜子(用L2表示)开始,关闭相隔为1的柜子。学生S3从第三个柜子开始,然后改变每第三个柜子(如果他是开的就关上,如果他是关的就打开)。学生S4从柜子L4开始,然后改变每第四个柜子的开闭状态。学生S5从L5开始,然后改变每第五个柜子的状态,以此类推,知道学生S100改变L100为止。
在所有学生都经过教学楼并且改变了柜子之后,哪些柜子是开的?编写程序找到答案,并显示所有打开的储物柜号,以一个空格隔开。
提示:使用包含100个布尔型元素的数值,每个元素都表明一个柜子是开的(true)还是关的(false)。初始状态时,所有的柜子都是关的。
*7.23(Game: locker problem)There are 100 lockers and 100 students in the school. All the lockers are closed on the first day of school. As the students come in, a dead student (denoted by S1) opens each cabinet. Then, the second student (denoted by S2) understands the second cabinet (represented by L2) and begins to close the cupboard separated by 1. Student S3 starts with the third cabinet, then changes every third cabinet (close it if it’s open, open it if it’s closed). Student S4 starts with cabinet L4 and changes the opening and closing status of each fourth cabinet. Student S5 starts from L5, then changes the state of every fifth cabinet, and so on until student S100 changes L100.
After all the students have passed the teaching building and changed the cabinets, which cabinets are open? Write a program to find the answer and display all open locker numbers, separated by a space.
Tip: use a value of 100 Boolean elements, each of which indicates whether a cabinet is on (true) or off (false). In the initial state, all cabinets are closed. -
参考代码:
package chapter07; public class Code_23 { public static void main(String