Imagine a row of 100 closed doors. Now, make 100 passes along the row, and at each pass "toggle" the doors whose number is divisible by the number of the pass. (
By "toggle", we mean to open a closed door, or close an opened one.)
For example, on the first pass, we will toggle all the doors, on the second, we will toggle only the even-numbered doors, on the third - only doors whose number is divisible by three, and so on.
At the end of the 100 passes, how many doors will be left open?
(from techInterview.org)
The answer is one... one door will be left ajar after the 100 passes... The rational behind it is simple... Each door is closed by the time it's door number is the same as the number of passes... As the number of passes increase, some doors can no longer be toggled because their door number is too small to be divided... for instance the third door is opened on the first pass and closed on the third. It can no longer be opened after that... The eight door is opened on the first pass, closed on the second, opened on the fourth and closed on the eight... After that it is no longer opened... So if we follow this rule, the only door left opened after 100 passes is the first which is opened on the first pass and then never touched again... Happy solving!!