You have 100 doors in a row that are all initially closed. You make 100 passes by the doors.
a) The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it).
b) The second time you only visit every 2nd door (door #2, #4, #6, ...).
c) The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Question: What state are the doors in after the last pass? Which doors are open?
var doors : array [1..100] of Boolean;
var i, j : Integer;
begin
for i := 1 to 100 do
for j := i to 100 do
if (j mod i) = 0 then
doors[j] := not doors[j];
for i := 1 to 100 do
if doors[i] then
WriteLn('Door '+IntToStr(i)+' is open');
end;
{
Door 1 is open
Door 4 is open
Door 9 is open
Door 16 is open
Door 25 is open
Door 36 is open
Door 49 is open
Door 64 is open
Door 81 is open
Door 100 is open
}
|
var doors = function () {
for (var r=[],i=0; i<100; i++) r.push(false);
return r
}();
var i = 0;
var j = 0;
for(i=1;i<=100;i++) {
for(j=i;j<=100;j++) {
if (!(j%i)) {
doors[(j)-1] = !doors[(j)-1];
}
}
}
for(i=1;i<=100;i++) {
if (doors[(i)-1]) {
document.writeln(("Door "+i.toString()+" is open"));
}
}
|
|