100 doors

Question

There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed,open it;if it is open,close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...),and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc,until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?

先把问题缩小: 10道门关着,按以上方式遍历这些门10次。 最后很明显,第一道们肯定是开着的;第二、第三是关着的! X道门的开关次数跟X的约数有关,如果X有偶数个约数则门最终的状态是关着的,否则为开着的。

问题现在变成: 1 到 100 之间公约数个数为奇数的数字是?

[i * i for i in range(1, int(math.sqrt(100)) + 1)] // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Java Solution

public class Doors 
{
	public static void main(String[] args)
	{
		for(int i=0;i<10;i++)
			System.out.println("Door #"+(i + 1)*(i + 1) +" is open.");
	}
}
posted @ 2016-10-17 13:41  邓晓锋  阅读(339)  评论(0编辑  收藏  举报