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?


Alternate:
As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares.

Opening only those doors is an   optimization   that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.




 
WITH    OneToTen (N)
AS  (   SELECT  N
        FROM (  VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)
                ) V(N)
        )
    ,   InitDoors (Num, IsOpen)
AS  (   SELECT  1
            +   1 * Units.N
            +   10 * Tens.N AS Num
            ,   CONVERT(Bit, 0) AS IsOpen
        FROM    OneToTen AS Units
        CROSS JOIN  OneToTen AS Tens
        ) -- This part could be easier with a tally table or equivalent table-valued function
    ,   States (NbStep, Num, IsOpen)
AS  (   SELECT  0 AS NbStep
            ,   Num
            ,   IsOpen
        FROM    InitDoors AS InitState
        UNION ALL
        SELECT  1 + NbStep
            ,   Num
            ,   CASE Num % (1 + NbStep)
                    WHEN 0 THEN ~IsOpen
                    ELSE IsOpen
                END
        FROM    States
        WHERE   NbStep < 100
        )
SELECT  Num AS DoorNumber
    ,   Concat( 'Door number ', Num, ' is '
            ,   CASE IsOpen
                    WHEN 1 THEN ' open'
                    ELSE ' closed'
                END ) AS RESULT -- Concat needs SQL Server 2012
FROM    States
WHERE   NbStep = 100
ORDER BY Num
; -- Fortunately, maximum recursion is 100 in SQL Server.
-- For more doors, the MAXRECURSION hint should be used.
-- More doors would also need an InitDoors with more rows.
 