I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# 100 doors

100 doors
You are encouraged to solve this task according to the task description, using any language you may know.

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.

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.

## 11l

Translation of: Python
V doors = [0B] * 100L(i) 100   L(j) (i .< 100).step(i + 1)      doors[j] = !doors[j]   print(‘Door ’(i + 1)‘: ’(I doors[i] {‘open’} E ‘close’))

## 360 Assembly

*        100 doors                 13/08/2015HUNDOOR  CSECT         USING  HUNDOOR,R12         LR     R12,R15         LA     R6,0         LA     R8,1               step 1         LA     R9,100LOOPI    BXH    R6,R8,ELOOPI       do ipass=1 to 100 (R6)         LR     R7,R6         SR     R7,R6         LR     R10,R6             step ipass         LA     R11,100LOOPJ    BXH    R7,R10,ELOOPJ      do idoor=ipass to 100 by ipass (R7)         LA     R5,DOORS-1         AR     R5,R7         XI     0(R5),X'01'        doors(idoor)=not(doors(idoor))NEXTJ    B      LOOPJELOOPJ   B      LOOPIELOOPI   LA     R10,BUFFER         R10 address of the buffer         LA     R5,DOORS           R5 address of doors item         LA     R6,1               idoor=1 (R6)         LA     R9,100             loop counterLOOPN    CLI    0(R5),X'01'        if doors(idoor)=1         BNE    NEXTN         XDECO  R6,XDEC            idoor to decimal         MVC    0(4,R10),XDEC+8    move decimal to buffer         LA     R10,4(R10)NEXTN	 LA     R6,1(R6)           idoor=idoor+1         LA     R5,1(R5)         BCT    R9,LOOPN           loopELOOPN   XPRNT  BUFFER,80RETURN   XR     R15,R15         BR     R14DOORS    DC     100X'00'BUFFER   DC     CL80' 'XDEC     DS     CL12         YREGS         END    HUNDOOR
Output:
   1   4   9  16  25  36  49  64  81 100

## 4DOS Batch

 @echo offset doors=%@repeat[C,100]do step = 1 to 100  do door = %step to 100 by %step    set doors=%@left[%@eval[%door-1],%doors]%@if[%@instr[%@eval[%door-1],1,%doors]==C,O,C]%@right[%@eval[100-%door],%doors]  enddoenddo

The SET line consists of three functions:

 %@left[n,string]                      ^: Return n leftmost chars in string%@right[n,string]                     ^: Return n rightmost chars in string%@if[condition,true-val,false-val]    ^: Evaluate condition; return true-val if true, false-val if false

Here @IF is used to toggle between C and O.

## 6502 Assembly

Works with: [www.6502asm.com] version beta

unoptimized Based on BASIC QB64 unoptimized version

; 100 DOORS in  6502 assembly language for: http://www.6502asm.com/beta/index.html; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version.; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC;; Notes:;    Doors array[1..100] is at $0201..$0264. On the specified emulator, this is in video memory, so tbe results will ; be directly shown as pixels in the display.;    $0200 (door 0) is cleared for display purposes but is not involved in the open/close loops.; Y register holds Stride; X register holds Index; Zero Page address$01 used to add Stride to Index (via A) because there's no add-to-X or add-Y-to-A instruction.   ; First, zero door array    LDA #00    LDX #100Z_LOOP:    STA 200,X    DEX    BNE Z_LOOP    STA 200,X   ; Now do doors repeated open/close    LDY #01        ; Initial value of StrideS_LOOP:    CPY #101    BCS S_DONE    TYA            ; Initial value of IndexI_LOOP:    CMP #101    BCS I_DONE    TAX            ; Use as Door array index    INC $200,X ; Toggle bit 0 to reverse state of door STY 01 ; Add stride (Y) to index (X, via A) ADC 01 BCC I_LOOPI_DONE: INY BNE S_LOOPS_DONE: ; Finally, format array values for output: 0 for closed, 1 for open LDX #100C_LOOP: LDA$200,X    AND #$01 STA$200,X    DEX    BNE C_LOOP

48. bytes of code; the specified emulator does not report cycles.

Works with: [6502asm.com] version 1.2

optimized Largely inspired by the optimized C implementation - makes use of the fact that finally only the doors whose numbers are squares of integers are open, as well as the fact that

$n^{2}=1+3+5+\ldots +(2n-1)$.


## AutoHotkey

### Standard Approach

Loop, 100  Door%A_Index% := "closed" Loop, 100 {  x := A_Index, y := A_Index  While (x <= 100)  {    CurrentDoor := Door%x%    If CurrentDoor contains closed    {      Door%x% := "open"      x += y    }    else if CurrentDoor contains open    {      Door%x% := "closed"      x += y    }  }} Loop, 100 {   CurrentDoor := Door%A_Index%   If CurrentDoor contains open      Res .= "Door " A_Index " is openn"}MsgBox % Res

### Alternative Approach

Making use of the identity:

$\sum _{i=1}^{n}(2i-1)=n^{2}$

increment := 3, square := 1 Loop, 100     If (A_Index = square)         outstring .= "nDoor " A_Index " is open"         ,square += increment, increment += 2 MsgBox,, Succesfull, % SubStr(outstring, 2)

### Optimized

While (Door := A_Index ** 2) <= 100   Result .= "Door " Door " is openn"MsgBox, %Result%

## AutoIt

 #include <array.au3>$doors = 100 ;door array, 0 = closed, 1 = openLocal$door[$doors +1] For$ii = 1 To $doors For$i = $ii To$doors Step $ii$door[$i] = Not$door[$i] nextNext ;display to screenFor$i = 1 To $doors ConsoleWrite (Number($door[$i])& " ") If Mod($i,10) = 0 Then ConsoleWrite(@CRLF)Next 

## AWK

unoptimized

BEGIN {  for(i=1; i <= 100; i++)  {    doors[i] = 0 # close the doors  }  for(i=1; i <= 100; i++)  {    for(j=i; j <= 100; j += i)    {      doors[j] = (doors[j]+1) % 2    }  }  for(i=1; i <= 100; i++)  {    print i, doors[i] ? "open" : "close"  }}

optimized

BEGIN {  for(i=1; i <= 100; i++) {    doors[i] = 0 # close the doors  }  for(i=1; i <= 100; i++) {    if ( int(sqrt(i)) == sqrt(i) ) {      doors[i] = 1    }  }  for(i=1; i <= 100; i++)  {    print i, doors[i] ? "open" : "close"  }}

## Axiom

Unoptimized:
(open,closed,change,open?) := (true,false,not,test);doors := bits(100,closed);for i in 1..#doors repeat  for j in i..#doors by i repeat    doors.j := change doors.j[i for i in 1..#doors | open? doors.i] 
Optimized:
[i for i in 1..100 | perfectSquare? i] -- or[i^2 for i in 1..sqrt(100)::Integer]

## B

Works with: The Amsterdam Compiler Kit - B version V6.1pre1
main(){  auto doors; /* != 0 means open */  auto pass, door;   door = 0;  while( door<100 ) doors[door++] = 0;   pass = 0;  while( pass<100 )  {    door = pass;    while( door<100 )    {      doors[door] = !doors[door];      door =+ pass+1;    }    ++pass;  }   door = 0;  while( door<100 )  {    printf("door #%d is %s.*n", door+1, doors[door] ? "open" : "closed");    ++door;  }   return(0);}

## BaCon

 OPTION BASE 1 DECLARE doors FOR size = 1 TO 100    FOR pass = 0 TO 100 STEP size	doors[pass] = NOT(doors[pass])    NEXTNEXT FOR which = 1 TO 100    IF doors[which] THEN PRINT whichNEXT 
Output:
1
4
9
16
25
36
49
64
81
100


## BASIC

### Applesoft BASIC

Based on the Sinclair ZX81 BASIC implementation.

  100 : 110  REM  100 DOORS PROBLEM 120 : 130  DIM D(100) 140  FOR P = 1 TO 100 150  FOR T = P TO 100 STEP P 160  D(T) =  NOT D(T): NEXT T 170  NEXT P 180  FOR I = 1 TO 100 190  IF D(I) THEN  PRINT I;" "; 200  NEXT I 
Output:

]RUN
1 4 9 16 25 36 49 64 81 100

### BASIC256

# 100 doors problemdim d(100) # simple solutionprint "simple solution"gosub initializefor t = 1 to 100   for j = t to 100 step t      d[j-1] = not d[j-1]   next jnext tgosub showopen # more optimized solutionprint "more optimized solution"gosub initializefor t = 1 to 10      d[t^2-1] = truenext tgosub showopenend initialize:for t = 1 to d[?]   d[t-1] = false	 # closednext treturn showopen:for t = 1 to d[?]   print d[t-1]+ " ";   if t%10 = 0 then printnext treturn

### Commodore BASIC

Based on the Sinclair ZX81 BASIC implementation.

10 DIM D(100)20 FOR I=1 TO 10030 FOR J=I TO 100 STEP I40 D(J) = NOT D(J)50 NEXT J60 NEXT I70 FOR I=1 TO 10080 IF D(I) THEN PRINT I,90 NEXT I

### IS-BASIC

100 PROGRAM "100doors.bas"110 NUMERIC D(1 TO 100)120 FOR I=1 TO 100130   LET D(I)=0140 NEXT150 FOR I=1 TO 100160   FOR J=I TO 100 STEP I170     LET D(J)=NOT D(J)180   NEXT 190 NEXT200 FOR I=1 TO 100210   IF D(I) THEN PRINT I220 NEXT

Optimized:

100 PROGRAM "100doors.bas"110 LET NR=1:LET D=3120 DO130   PRINT NR140   LET NR=NR+D:LET D=D+2150 LOOP WHILE NR<=100

### QBASIC

Works with: QBASIC, QB64

unoptimized

REM "100 Doors" program FOR QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler.REM Author: G. A. TipperyREM Date: 12-Feb-2014REMREM   Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors DEFINT A-ZCONST N = 100DIM door(N) FOR stride = 1 TO N    FOR index = stride TO N STEP stride        LET door(index) = NOT (door(index))    NEXT indexNEXT stride PRINT "Open doors:"FOR index = 1 TO N    IF door(index) THEN PRINT indexNEXT index END
Works with: QuickBasic version 4.5

unoptimized

DIM doors(0 TO 99)FOR pass = 0 TO 99	FOR door = pass TO 99 STEP pass + 1		PRINT doors(door)		PRINT NOT doors(door)		doors(door) = NOT doors(door)	NEXT doorNEXT passFOR i = 0 TO 99	PRINT "Door #"; i + 1; " is ";	IF NOT doors(i) THEN		PRINT "closed"	ELSE		PRINT "open"	END IFNEXT i

optimized

DIM doors(0 TO 99)FOR door = 0 TO 99	IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1NEXT doorFOR i = 0 TO 99	PRINT "Door #"; i + 1; " is ";	IF NOT doors(i) THEN		PRINT "closed"	ELSE		PRINT "open"	END IFNEXT i

### Sinclair ZX81 BASIC

Works with only 1k of RAM, although it doesn't leave too much to play with.

10 DIM D(100)20 FOR I=1 TO 10030 FOR J=I TO 100 STEP I40 LET D(J)=NOT D(J)50 NEXT J60 NEXT I70 FOR I=1 TO 10080 IF D(I) THEN PRINT I,90 NEXT I

## Batch File

unoptimized

 @echo offsetlocal enableDelayedExpansion:: 0 = closed:: 1 = open:: SET /A treats undefined variable as 0:: Negation operator ! must be escaped because delayed expansion is enabledfor /l %%p in (1 1 100) do for /l %%d in (%%p %%p 100) do set /a "door%%d=^!door%%d"for /l %%d in (1 1 100) do if !door%%d!==1 (  echo door %%d is open) else echo door %%d is closed 

optimized

 @echo offsetlocal enableDelayedExpansionset /a square=1, incr=3for /l %%d in (1 1 100) do (  if %%d neq !square! (echo door %%d is closed) else (    echo door %%d is open    set /a square+=incr, incr+=2  )) 

## BBC BASIC

      DIM doors%(100)       FOR pass% = 1 TO 100        FOR door% = pass% TO 100 STEP pass%          doors%(door%) = NOT doors%(door%)        NEXT door%      NEXT pass%       FOR door% = 1 TO 100        IF doors%(door%) PRINT "Door " ; door% " is open"      NEXT door%

## bc

/* 0 means door is closed, 1 means door is open */for (i = 0; i < 100; i++) {    for (j = i; j < 100; j += (i + 1)) {        d[j] = 1 - d[j]     /* Toggle door */    }} "Open doors:"for (i = 0; i < 100; i++) {    if (d[i] == 1) (i + 1)}

## Befunge

### Befunge-93

#### Unoptimized

Requires an interpreter with working read-write memory support. Padding the code page with extra blank lines can sometimes help.

>"d">:00p1-:>:::9%\9/9+g2%!\:9v$.v_^#!$::$_^#"c":+g00p+9/9\%<::<[email protected]#$:\*:+55:+1p27g1g+9/9\%9 

#### Optimized

Just calculates the first 10 perfect squares.

1+:::*.9#@_

### Befunge-98

Works with: CCBI version 2.1
108p0>:18p;;>:9g!18g9p08g]*!0\|+relet|-1*aap81::+];::+1<r]!g9;>$08g1+:08paa[*#@_^._aa ## BlitzMax Works with: BlitzMax version 1.37 optimized Graphics 640,480i=1While ((i*i)<=100) a$=i*i	DrawText a$,10,20*i Print i*i i=i+1 WendFlip WaitKey  ## BlooP The currently available BlooP interpreters don't really allow iterating over cells with any level of ease, so instead I loop over each door in turn, running it through all 100 cycles and toggling it when it is a multiple of the step number.  DEFINE PROCEDURE ''DIVIDE'' [A,B]:BLOCK 0: BEGIN IF A < B, THEN: QUIT BLOCK 0; CELL(0) <= 1; OUTPUT <= 1; LOOP AT MOST A TIMES: BLOCK 2: BEGIN IF OUTPUT * B = A, THEN: QUIT BLOCK 0; OUTPUT <= OUTPUT + 1; IF OUTPUT * B > A, THEN: BLOCK 3: BEGIN OUTPUT <= CELL(0); QUIT BLOCK 0; BLOCK 3: END; CELL(0) <= OUTPUT; BLOCK 2: END;BLOCK 0: END. DEFINE PROCEDURE ''MINUS'' [A,B]:BLOCK 0: BEGIN IF A < B, THEN: QUIT BLOCK 0; LOOP AT MOST A TIMES: BLOCK 1: BEGIN IF OUTPUT + B = A, THEN: QUIT BLOCK 0; OUTPUT <= OUTPUT + 1; BLOCK 1: END;BLOCK 0: END. DEFINE PROCEDURE ''MODULUS'' [A,B]:BLOCK 0: BEGIN CELL(0) <= DIVIDE[A,B]; OUTPUT <= MINUS[A,CELL(0) * B];BLOCK 0: END. DEFINE PROCEDURE ''TOGGLE'' [DOOR]:BLOCK 0: BEGIN IF DOOR = 1, THEN: QUIT BLOCK 0; OUTPUT <= 1;BLOCK 0: END. DEFINE PROCEDURE ''NUMBERS'' [DOOR, COUNT]:BLOCK 0: BEGIN CELL(0) <= 1; /*each number*/ OUTPUT <= 0; /*current door state*/ LOOP COUNT TIMES: BLOCK 1: BEGIN IF MODULUS[DOOR, CELL(0)] = 0, THEN: OUTPUT <= TOGGLE[OUTPUT]; CELL(0) <= CELL(0) + 1; BLOCK 1: END; BLOCK 0: END. DEFINE PROCEDURE ''DOORS'' [COUNT]:BLOCK 0: BEGIN CELL(0) <= 1; /*each door*/ LOOP COUNT TIMES: BLOCK 1: BEGIN CELL(1) <= NUMBERS[CELL(0), COUNT]; /*iterate over the states of this door to get its final state*/ IF CELL(1) = 1, THEN: /*door state = open*/ PRINT[CELL(0), ' ']; CELL(0) <= CELL(0) + 1; BLOCK 1: END;BLOCK 0: END. DOORS;  Output:  > 1 > 4 > 9 > 16 > 25 > 36 > 49 > 64 > 81 > 100  ## Bracmat Bracmat is not really at home in tasks that involve addressing things by index number. Here are four solutions that each do the task, but none should win a price for cleanliness. Solution 1. Use an indexable array. Local variables are stored in stacks. Each stack corresponds to one variable name and vice versa. Stacks can also be used as arrays, but because of how local variables are implemented, arrays cannot be declared as local variables. ( 100doors-tbl= door step . tbl$(doors.101) { Create an array. Indexing is 0-based. Add one extra for addressing element nr. 100 }    & 0:?step    &   whl      ' ( 1+!step:~>100:?step   { ~> means 'not greater than', i.e. 'less than or equal' }        & 0:?door        &   whl          ' ( !step+!door:~>100:?door            & 1+-1*!(!door$doors):?doors { <number>$<variable> sets the current index, which stays the same until explicitly changed. }            )        )    & 0:?door    &   whl      ' ( 1+!door:~>100:?door        &   out          $( door !door is ( !(!door$doors):1&open              | closed              )            )        )    & tbl$(doors.0) { clean up the array }) Solution 2. Use one variable for each door. In Bracmat, a variable name can be any non-empty string, even a number, so we use the numbers 1 .. 100 as variable names, but also as door numbers. When used as variable an extra level of indirection is needed. See the occurrences of ?! and !! in the following code. ( 100doors-var= step door . 0:?door & whl ' ( 1+!door:~>100:?door & closed:?!door { this creates a variable and assigns a value 'closed' to it } ) & 0:?step & whl ' ( 1+!step:~>100:?step & 0:?door & whl ' ( !step+!door:~>100:?door & ( !!door:closed&open | closed ) : ?!door ) ) & 0:?door & whl ' ( 1+!door:~>100:?door & out$(door !door is !!door)        )    & 0:?door    &   whl      ' ( 1+!door:~>100:?door        & tbl$(!door.0) { cleanup the variable } )) Solution 3. Use a list and a dedicated positioning pattern to address the right door in the list. Create a new list by concatenating the skipped elements with the toggled elements. This solution is computationally unfavourable because of the many concatenations. ( 100doors-list= doors door doorIndex step . :?doors & 0:?door & whl ' ( 1+!door:~>100:?door & closed !doors:?doors ) & 0:?skip & whl ' ( :?ndoors & whl ' ( !doors:?skipped [!skip %?door ?doors { the [<number> pattern only succeeds when the scanning cursor is at position <number> } & !ndoors !skipped ( !door:open&closed | open ) : ?ndoors ) & !ndoors !doors:?doors & 1+!skip:<100:?skip ) & out$!doors)

Solution 4. Use a list of objects. Each object can be changed without the need to re-create the whole list.

( 100doors-obj=   doors door doorIndex step  .   :?doors    & 0:?door    &   whl      ' ( 1+!door:~>100:?door        & new$(=closed) !doors:?doors ) & 0:?skip & whl ' ( !doors:?tododoors & whl ' ( !tododoors:? [!skip %?door ?tododoors & ( !(door.):open&closed | open ) : ?(door.) ) & 1+!skip:<100:?skip ) & out$!doors)

These four functions are called in the following way:

100doors-tbl$& 100doors-var$& 100doors-list$& 100doors-obj$;

## Burlesque

Version using square numbers:

 blsq ) 10ro2?^{1 4 9 16 25 36 49 64 81 100} 

## C

### unoptimized

Uses: C Runtime (Components:printf,)
#include <stdio.h> int main(){  char is_open = { 0 };  int pass, door;   /* do the 100 passes */  for (pass = 0; pass < 100; ++pass)    for (door = pass; door < 100; door += pass+1)      is_open[door] = !is_open[door];   /* output the result */  for (door = 0; door < 100; ++door)    printf("door #%d is %s.\n", door+1, (is_open[door]? "open" : "closed"));   return 0;}

Using defensive programming, pointers, sentinel values and some other standard programming practices,

Uses: C Runtime (Components:printf,)
#include <stdio.h> #define NUM_DOORS 100 int main(int argc, char *argv[]){  int is_open[NUM_DOORS] = { 0 } ;  int * doorptr, * doorlimit = is_open + NUM_DOORS ;  int pass ;   /* do the N passes, go backwards because the order is not important */  for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) {    for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) {      ( * doorptr ) ^= 1 ;    }  }   /* output results */  for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) {    printf("door #%lld is %s\n", ( doorptr - is_open ) + 1, ( * doorptr ) ? "open" : "closed" ) ;  }}

### optimized

This optimized version makes use of the fact that finally only the doors with square index are open, as well as the fact that $n^{2}=1+3+5+\ldots +(2n-1)$.

Uses: C Runtime (Components:printf,)
#include <stdio.h> int main(){  int square = 1, increment = 3, door;  for (door = 1; door <= 100; ++door)  {    printf("door #%d", door);    if (door == square)    {      printf(" is open.\n");      square += increment;      increment += 2;    }    else      printf(" is closed.\n");  }  return 0;}

The following ultra-short optimized version demonstrates the flexibility of C loops, but isn't really considered good C style:

#include <stdio.h> int main(){  int door, square, increment;  for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2))    printf("door #%d is %s.\n", door, (door == square? "open" : "closed"));  return 0;}
Or really optimize it -- square of an integer is, well, computable:
#include <stdio.h> int main(){	int i;	for (i = 1; i * i <= 100; i++)		printf("door %d open\n", i * i); 	return 0;}

## C#

### Unoptimized with Modulus % Operator

namespace ConsoleApplication1{    using System;    class Program    {        static void Main(string[] args)        {            bool[] doors = new bool;             //Close all doors to start.            for (int d = 0; d < 100; d++) doors[d] = false;             //For each pass...            for (int p = 0; p < 100; p++)//number of passes            {                //For each door to toggle...                for (int d = 0; d < 100; d++)//door number                {                    if ((d + 1) % (p + 1) == 0)                    {                        doors[d] = !doors[d];                    }                }            }             //Output the results.            Console.WriteLine("Passes Completed!!!  Here are the results: \r\n");            for (int d = 0; d < 100; d++)            {                if (doors[d])                {                    Console.WriteLine(String.Format("Door #{0}: Open", d + 1));                }                else                {                    Console.WriteLine(String.Format("Door #{0}: Closed", d + 1));                }            }            Console.ReadKey(true);        }    }}

### Optimized for Orthogonality

(This version demonstrates a different thought pattern during development, where operation and presentation are separated. It could easily be refactored so that the operations to determine which doors are opened and to display the list of doors would be in separate methods, at which point it would become simple to extract them to separate classes and employ a DI pattern to switch the algorithm or display mechanism being used. It also keeps the calculation clear and concise.)

namespace ConsoleApplication1{    using System;    class Program    {        static void Main(string[] args)        {            //Perform the operation.            bool[] doors = new bool;            int n = 0;            int d;            while ((d = (++n * n)) <= 100)                doors[d - 1] = true;             //Perform the presentation.            for (d = 0; d < doors.Length; d++)                Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed");            Console.ReadKey(true);        }    }}

### Unoptimized but Concise

namespace ConsoleApplication1{    using System;    class Program    {        static void Main()        {            bool[] doors = new bool;             //The number of passes can be 1-based, but the number of doors must be 0-based.            for (int p = 1; p <= 100; p++)                for (int d = p - 1; d < 100; d += p)                    doors[d] = !doors[d];            for (int d = 0; d < 100; d++)                Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed");            Console.ReadKey(true);        }    }}

### Optimized for brevity

namespace ConsoleApplication1{    using System;    class Program    {        static void Main()        {            double n;             //If the current door number is the perfect square of an integer, say it is open, else say it is closed.            for (int d = 1; d <= 100; d++)                Console.WriteLine("Door #{0}: {1}", d, (n = Math.Sqrt(d)) == (int)n ? "Open" : "Closed");            Console.ReadKey(true);        }    }}

## C++

Works with: GCC version 4.1.2 20061115 (prerelease) (SUSE Linux)

unoptimized

#include <iostream> int main(){  bool is_open = { false };   // do the 100 passes  for (int pass = 0; pass < 100; ++pass)    for (int door = pass; door < 100; door += pass+1)      is_open[door] = !is_open[door];   // output the result  for (int door = 0; door < 100; ++door)    std::cout << "door #" << door+1 << (is_open[door]? " is open." : " is closed.") << std::endl;  return 0;}

optimized This optimized version makes use of the fact that finally only the doors with square index are open, as well as the fact that $(n+1)^{2}=1+3+5+\ldots +(2n+1)$.

#include <iostream> int main(){  int square = 1, increment = 3;  for (int door = 1; door <= 100; ++door)  {    std::cout << "door #" << door;    if (door == square)    {      std::cout << " is open." << std::endl;      square += increment;      increment += 2;    }    else      std::cout << " is closed." << std::endl;  }  return 0;}

The only calculation that's really needed:

#include <iostream> //compiled with "Dev-C++" , from RaptorOne int main(){    for(int i=1; i*i<=100; i++)            std::cout<<"Door "<<i*i<<" is open!"<<std::endl;}

Compile time computation using C++17 to produce fastest runtime.

#include <iostream>    // compiled with clang (tags/RELEASE_600/final)#include <type_traits> // or g++ (GCC) 7.3.1 20180406 -- from hare1039namespace functional_list // basic building block for template meta programming{struct NIL{	using head = NIL;	using tail = NIL;	friend std::ostream& operator << (std::ostream& os, NIL const) { return os; }}; template <typename H, typename T = NIL>struct list{	using head = H;	using tail = T;}; template <int i>struct integer{	static constexpr int value = i;	friend std::ostream& operator << (std::ostream& os, integer<i> const) { os << integer<i>::value; return os;}}; template <typename L, int nTH> constexprauto at(){	if constexpr (nTH == 0)		return (typename L::head){};	else if constexpr (not std::is_same_v<typename L::tail, NIL>) 		return at<typename L::tail, nTH - 1>();	else		return NIL{};}template <typename L, int nTH>using at_t = decltype(at<L, nTH>()); template <typename L, typename elem> constexprauto prepend() { return list<elem, L>{}; } template <typename L, typename elem>using prepend_t = decltype(prepend<L, elem>()); template <int Size, typename Dat = integer<0>> constexprauto gen_list(){	if constexpr (Size == 0)		return NIL{};	else	{		using next = decltype(gen_list<Size - 1, Dat>());		return prepend<next, Dat>();	}}template <int Size, typename Dat = integer<0>>using gen_list_t = decltype(gen_list<Size, Dat>()); } namespace fl = functional_list; constexpr int door_amount = 101; // index from 1 to 100 template <typename L, int current, int moder> constexprauto construct_loop(){	using val_t = fl::at_t<L, current>;	if constexpr (std::is_same_v<val_t, fl::NIL>)		return fl::NIL{};	else	{		constexpr int val = val_t::value;		using val_add_t = fl::integer<val + 1>;		using val_old_t = fl::integer<val>; 		if constexpr (current == door_amount)		{			if constexpr(current % moder == 0)				return fl::list<val_add_t>{};			else				return fl::list<val_old_t>{};		}		else		{			using sub_list = decltype(construct_loop<L, current + 1, moder>());			if constexpr(current % moder == 0)				return fl::prepend<sub_list, val_add_t>();			else				return fl::prepend<sub_list, val_old_t>();		}	}} template <int iteration> constexprauto construct(){	if constexpr (iteration == 1) // door index = 1	{		using l = fl::gen_list_t<door_amount>;		return construct_loop<l, 0, iteration>();	}	else	{		using prev_iter_list = decltype(construct<iteration - 1>());		return construct_loop<prev_iter_list, 0, iteration>();	}} template <typename L, int pos> constexprvoid show_ans(){	if constexpr (std::is_same_v<typename L::head, fl::NIL>)		return;	else	{		if constexpr (L::head::value % 2 == 1)			std::cout << "Door " << pos << " is opened.\n";		show_ans<typename L::tail, pos + 1>();	}} int main(){	using result = decltype(construct<100>());	show_ans<result, 0>();}

## C1R

100_doors

## Caché ObjectScript

  for i=1:1:100 {	 set doors(i) = 0 } for i=1:1:100 {	 for door=i:i:100 {		  Set doors(door)='doors(door)	 } } for i = 1:1:100 {	if doors(i)=1 write i_": open",! } 

Output:

 1: open4: open9: open16: open25: open36: open49: open64: open81: open100: open 

## Ceylon

shared void run() {    print("Open doors (naive):     naive()           Open doors (optimized): optimized()"); } shared {Integer*} naive(Integer count = 100) {    variable value doors = [ for (_ in 1..count) closed ];    for (step in 1..count) {        doors = [for (i->door in doors.indexed) let (index = i+1) if (step == 1 || step.divides(index)) then door.toggle() else door ];    }    return doors.indexesWhere((door) => door == opened).map(1.plusInteger);} shared {Integer*} optimized(Integer count = 100) =>        { for (i in 1..count) i*i }.takeWhile(count.notSmallerThan);  shared abstract class Door(shared actual String string) of opened | closed {    shared formal Door toggle();}object opened extends Door("opened") { toggle() => closed; }object closed extends Door("closed") { toggle() => opened; }

Output:

Open doors (naive):     { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }
Open doors (optimized): { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }

## Clarion

     program     map    end MAX_DOOR_NUMBER         equate(100)CRLF                    equate('<13,10>') Doors                   byte,dim(MAX_DOOR_NUMBER)Pass                    byteDoorNumber              byteDisplayString           cstring(2000) ResultWindow            window('Result'),at(,,133,291),center,double,auto                            prompt('Door states:'),at(8,4),use(?PromptTitle)                            text,at(8,16,116,266),use(DisplayString),boxed,vscroll,font('Courier New',,,,CHARSET:ANSI),readonly                        end     code     Doors :=: false    loop Pass = 1 to MAX_DOOR_NUMBER        loop DoorNumber = Pass to MAX_DOOR_NUMBER by Pass            Doors[DoorNumber] = choose(Doors[DoorNumber], false, true)        end    end     clear(DisplayString)    loop DoorNumber = 1 to MAX_DOOR_NUMBER        DisplayString = DisplayString & format(DoorNumber, @n3) & ' is ' & choose(Doors[DoorNumber], 'opened', 'closed') & CRLF    end    open(ResultWindow)    accept    end    close(ResultWindow)     return 

## Clio

Unoptimized

fn visit-doors doors step:  if step > 100: doors  else:    [1:100]      -> * fn index:            if index % step: doors[(index - 1)]            else: not doors[(index - 1)]      -> visit-doors (step + 1) [1:100] -> * n: false -> visit-doors 1 => doors[1:100] -> * (@eager) fn i:  doors[(i - 1)]    -> if = true: #open            else: #closed    -> print #Door i #is @

Optimized

[1:100] -> * (@eager) fn i:  i ^ 0.5    -> eq @ (transform i: floor)    -> if = true: #open            else: #closed    -> print #Door i #is @

## CLIPS

Unoptimized

(deffacts initial-state  (door-count 100)) (deffunction toggle  (?state)  (switch ?state    (case "open" then "closed")    (case "closed" then "open")  )) (defrule create-doors-and-visits  (door-count ?count)  =>  (loop-for-count (?num 1 ?count) do    (assert (door ?num "closed"))    (assert (visit-from ?num ?num))  )  (assert (doors initialized))) (defrule visit  (door-count ?max)  ?visit <- (visit-from ?num ?step)  ?door <- (door ?num ?state)  =>  (retract ?visit)  (retract ?door)  (assert (door ?num (toggle ?state)))  (if    (<= (+ ?num ?step) ?max)    then    (assert (visit-from (+ ?num ?step) ?step))  )) (defrule start-printing  (doors initialized)  (not (visit-from ? ?))  =>  (printout t "These doors are open:" crlf)  (assert (print-from 1))) (defrule print-door  (door-count ?max)  ?pf <- (print-from ?num)  (door ?num ?state)  =>  (retract ?pf)  (if    (= 0 (str-compare "open" ?state))    then    (printout t ?num " ")  )  (if    (< ?num ?max)    then    (assert (print-from (+ ?num 1)))    else    (printout t crlf "All other doors are closed." crlf)  ))

Optimized

(deffacts initial-state  (door-count 100)) (deffunction is-square  (?num)  (= (sqrt ?num) (integer (sqrt ?num)))) (defrule check-doors  (door-count ?count)  =>  (printout t "These doors are open:" crlf)  (loop-for-count (?num 1 ?count) do    (if (is-square ?num) then      (printout t ?num " ")    )  )  (printout t crlf "All other doors are closed." crlf))

## Clojure

Unoptimized / mutable array

(defn doors []  (let [doors (into-array (repeat 100 false))]    (doseq [pass   (range 1 101)             i      (range (dec pass) 100 pass) ]      (aset doors i (not (aget doors i))))    doors))    (defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n)) (defn print-open-doors []  (println     "Open doors after 100 passes:"    (apply str (interpose ", " (open-doors)))))

Unoptimized / functional

(defn doors []  (reduce (fn [doors toggle-idx] (update-in doors [toggle-idx] not))          (into [] (repeat 100 false))          (for [pass   (range 1 101)                i      (range (dec pass) 100 pass) ]            i))) (defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n)) (defn print-open-doors []  (println     "Open doors after 100 passes:"    (apply str (interpose ", " (open-doors)))))

Alternative Unoptimized / functional

(defn open-doors []  (->> (for [step (range 1 101), occ (range step 101 step)] occ)       frequencies       (filter (comp odd? val))       keys       sort)) (defn print-open-doors []  (println     "Open doors after 100 passes:"    (apply str (interpose ", " (open-doors)))))

Optimized / functional

(defn doors []	(reduce (fn [doors idx] (assoc doors idx true)) 	        (into [] (repeat 100 false))	        (map #(dec (* % %)) (range 1 11)))) (defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n)) (defn print-open-doors []  (println     "Open doors after 100 passes:"    (apply str (interpose ", " (open-doors)))))

Alternative Optimized / functional

(defn open-doors [] (->> (iterate inc 1) (map #(* % %)) (take-while #(<= % 100)))) (defn print-open-doors []  (println     "Open doors after 100 passes:"    (apply str (interpose ", " (open-doors)))))

## COBOL

       IDENTIFICATION DIVISION.       PROGRAM-ID. 100Doors.        DATA DIVISION.       WORKING-STORAGE SECTION.       01 Current-n      PIC 9(3).       01 StepSize       PIC 9(3).       01 DoorTable.          02 Doors       PIC 9(1)   OCCURS 100 TIMES.             88 ClosedDoor          VALUE ZERO.       01 Idx            PIC 9(3).        PROCEDURE DIVISION.       Begin.           INITIALIZE DoorTable           PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100             PERFORM VARYING Current-n FROM StepSize BY StepSize                     UNTIL Current-n > 100               SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n)             END-PERFORM           END-PERFORM            PERFORM VARYING Idx FROM 1 BY 1                   UNTIL Idx > 100             IF ClosedDoor (Idx)               DISPLAY Idx " is closed."             ELSE               DISPLAY Idx " is open."             END-IF           END-PERFORM            STOP RUN           .

## Coco

We use the naive algorithm.

doors = [false] * 100 for pass til doors.length    for i from pass til doors.length by pass + 1        ! = doors[i] for i til doors.length    console.log 'Door %d is %s.', i + 1, if doors[i] then 'open' else 'closed'

## CoffeeScript

unoptimized:

doors = [] for pass in [1..100]  for i in [pass..100] by pass    doors[i] = !doors[i] console.log "Doors #{index for index, open of doors when open} are open" # matrix outputconsole.log doors.map (open) -> +open 

optimized:

isInteger = (i) -> Math.floor(i) == i console.log door for door in [1..100] when isInteger Math.sqrt door

ultra-optimized:

console.log Math.pow(i,2) for i in [1..10]

## ColdFusion

Basic Solution: Returns List of 100 values: 1=open 0=closed

 	doorCount = 1;	doorList = "";	// create all doors and set all doors to open	while (doorCount LTE 100) {		doorList = ListAppend(doorList,"1");		doorCount = doorCount + 1;	}	loopCount = 2;	doorListLen = ListLen(doorList);	while (loopCount LTE 100) {		loopDoorListCount = 1;		while (loopDoorListCount LTE 100) {			testDoor = loopDoorListCount / loopCount;			if (testDoor EQ Int(testDoor)) {				checkOpen = ListGetAt(doorList,loopDoorListCount);				if (checkOpen EQ 1) {					doorList = ListSetAt(doorList,loopDoorListCount,"0");				} else {					doorList = ListSetAt(doorList,loopDoorListCount,"1");				}			}			loopDoorListCount = loopDoorListCount + 1;		}		loopCount = loopCount + 1;	} 

Squares of Integers Solution: Returns List of 100 values: 1=open 0=closed

 	doorCount = 1;	doorList = "";	loopCount = 1;	while (loopCount LTE 100) {		if (Sqr(loopCount) NEQ Int(Sqr(loopCount))) {			doorList = ListAppend(doorList,0);		} else {			doorList = ListAppend(doorList,1);		}		loopCount = loopCount + 1;	} 

Display only

// Display all doors<cfloop from="1" to="100" index="x">    Door #x# Open: #YesNoFormat(ListGetAt(doorList,x))#<br /></cfloop> // Output only open doors<cfloop from="1" to="100" index="x">    <cfif ListGetAt(doorList,x) EQ 1>        #x#<br />    </cfif></cfloop>

Another Route

<Cfparam name="doorlist" default=""><cfloop from="1" to="100" index="i">    <Cfset doorlist = doorlist & 'c,'></cfloop><cfloop from="1" to="100" index="i">    <Cfloop from="1" to="100" index="door" step="#i#">    <Cfif listgetat(doorlist, door) eq 'c'>        <Cfset doorlist = listsetat(doorlist, door, 'O')>    <Cfelse>        <Cfset doorlist = listsetat(doorlist, door, 'c')>    </Cfif>    </Cfloop></cfloop><Cfoutput>#doorlist#</Cfoutput>

 10 D=100: DIMD(D): P=120 PRINT CHR$(147);"PASS: ";P22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT30 IF P=100 THEN 4032 P=P+1: GOTO2040 PRINT: PRINT"THE FOLLOWING DOORS ARE OPEN: "42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI;44 NEXT  ## Common Lisp Unoptimized / functional This is a very unoptimized version of the problem, using recursion and quite considerable list-copying. It emphasizes the functional way of solving this problem. (defun visit-door (doors doornum value1 value2) "visits a door, swapping the value1 to value2 or vice-versa" (let ((d (copy-list doors)) (n (- doornum 1))) (if (eql (nth n d) value1) (setf (nth n d) value2) (setf (nth n d) value1)) d)) (defun visit-every (doors num iter value1 value2) "visits every 'num' door in the list" (if (> (* iter num) (length doors)) doors (visit-every (visit-door doors (* num iter) value1 value2) num (+ 1 iter) value1 value2))) (defun do-all-visits (doors cnt value1 value2) "Visits all doors changing the values accordingly" (if (< cnt 1) doors (do-all-visits (visit-every doors cnt 1 value1 value2) (- cnt 1) value1 value2))) (defun print-doors (doors) "Pretty prints the doors list" (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) (defun start (&optional (size 100)) "Start the program" (let* ((open "_") (shut "#") (doors (make-list size :initial-element shut))) (print-doors (do-all-visits doors size open shut)))) Unoptimized, imperative This is a version that closely follows the problem description and is still quite short. Of all the presented solutions it might be closest to "idiomatic Common Lisp". (define-modify-macro toggle () not) (defun 100-doors () (let ((doors (make-array 100))) (dotimes (i 100) (loop for j from i below 100 by (1+ i) do (toggle (svref doors j)))) (dotimes (i 100) (format t "door ~a: ~:[closed~;open~]~%" (1+ i) (svref doors i))))) Unoptimized, n-doors. (defun doors (z &optional (w (make-list z)) (n 1)) (if (> n z) w (doors z (toggle w n z) (1+ n)))) (defun toggle (w m z) (loop for a in w for n from 1 to z collect (if (zerop (mod n m)) (not a) a))) > (doors 100)(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T) Optimized, n-doors. (defun doors (n) (loop for a from 1 to n collect (zerop (mod (sqrt a) 1)))) > (doors 100)(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T) Optimized This is an optimized version, using the perfect square algorithm. (defun 100-doors () (let ((doors (make-array 100))) (dotimes (i 10) (setf (svref doors (* i i)) t)) (dotimes (i 100) (format t "door ~a: ~:[closed~;open~]~%" (1+ i) (svref doors i))))) Optimized 2 Another optimized version, with finer granular separation of functionality (might be a bit excessive). (defun perfect-square-list (n) "Generates a list of perfect squares from 0 up to n" (loop for i from 1 to (isqrt n) collect (expt i 2))) (defun print-doors (doors) "Pretty prints the doors list" (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) (defun open-door (doors num open) "Sets door at num to open" (setf (nth (- num 1) doors) open)) (defun visit-all (doors vlist open) "Visits and opens all the doors indicated in vlist" (dolist (dn vlist doors) (open-door doors dn open))) (defun start2 (&optional (size 100)) "Start the program" (print-doors (visit-all (make-list size :initial-element '\#) (perfect-square-list size) '_))) Optimized (2) This version displays a much more functional solution through the use of MAPCAR. (let ((i 0)) (mapcar (lambda (x) (if (zerop (mod (sqrt (incf i)) 1)) "_" "#")) (make-list 100))) ## Component Pascal BlackBox Component Builder  MODULE Doors100;IMPORT StdLog; PROCEDURE Do*;VAR i,j: INTEGER; closed: ARRAY 101 OF BOOLEAN;BEGIN (* initialization of closed to true *) FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END; (* process *) FOR i := 1 TO LEN(closed) DO; j := 1; WHILE j < LEN(closed) DO IF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j) END END; (* print results *) i := 1; WHILE i < LEN(closed) DO IF (i - 1) MOD 10 = 0 THEN StdLog.Ln END; IF closed[i] THEN StdLog.String("C ") ELSE StdLog.String("O ") END; INC(i) END;END Do;END Doors100.  Execute: ^Q Doors100.Do Output: O C C O C C C C O C C C C C C O C C C C C C C C O C C C C C C C C C C O C C C C C C C C C C C C O C C C C C C C C C C C C C C O C C C C C C C C C C C C C C C C O C C C C C C C C C C C C C C C C C C O  ## Coq Basic solution: Require Import List. Fixpoint rep {A} (a : A) n := match n with | O => nil | S n' => a::(rep a n') end. Fixpoint flip (l : list bool) (n k : nat) : list bool := match l with | nil => nil | cons h t => match k with | O => (negb h) :: (flip t n n) | S k' => h :: (flip t n k') end end. Definition flipeach l n := flip l n n. Fixpoint flipwhile l n := match n with | O => flipeach l 0 | S n' => flipwhile (flipeach l (S n')) n' end. Definition prison cells := flipwhile (rep false cells) cells. Optimized version ((n+1)^2 = n^2 + 2n + 1): Require Import List. Fixpoint prisoo' nd n k accu := match nd with | O => rev accu | S nd' => let ra := match k with | O => (true, S n, (n + n)) | S k' => (false, n, k') end in prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu) end. Definition prisoo cells := prisoo' cells 1 0 nil. Unit test: Goal prison 100 = prisoo 100. compute. reflexivity. Qed. Full proof at github: Goal forall n, prison n = prisoo n. Abort. ## Crystal doors = Array.new(100, false) 1.upto(100) do |i| i.step(by: i, limit: 100) do |j| doors[j - 1] = !doors[j - 1] endend doors.each_with_index do |open, i| puts "Door #{i + 1} is #{open ? "open" : "closed"}"end ## D import std.stdio, std.algorithm, std.range; enum DoorState : bool { closed, open }alias Doors = DoorState[]; Doors flipUnoptimized(Doors doors) pure nothrow { doors[] = DoorState.closed; foreach (immutable i; 0 .. doors.length) for (ulong j = i; j < doors.length; j += i + 1) if (doors[j] == DoorState.open) doors[j] = DoorState.closed; else doors[j] = DoorState.open; return doors;} Doors flipOptimized(Doors doors) pure nothrow { doors[] = DoorState.closed; for (int i = 1; i ^^ 2 <= doors.length; i++) doors[i ^^ 2 - 1] = DoorState.open; return doors;} void main() { auto doors = new Doors(100); foreach (const open; [doors.dup.flipUnoptimized, doors.dup.flipOptimized]) iota(1, open.length + 1).filter!(i => open[i - 1]).writeln;} Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Unoptimized. Demonstrates very basic language syntax/features. Program output allows to see what the code is doing:  import std.stdio; void printAllDoors(bool[] doors){ // Prints the state of all the doors foreach(i, door; doors) { writeln("#: ", i + 1, (door) ? " open" : " closed"); }}void main(){ bool doors = false; //Create 100 closed doors for(int a = 0; a < 100; ++a) { writefln("Pass #%s; visiting every %s door.", a + 1, a + 1); // Optional for(int i = a; i < 100; i += (a + 1)) { writefln("Visited door %s", i + 1); //Optional doors[i] = !doors[i]; } writeln(); // Optional } printAllDoors(doors); // Prints the state of each door}  ## Dafny The InitializeDoors function demonstrates some of Dafny's advanced features.  datatype Door = Closed | Open method InitializeDoors(n:int) returns (doors:array<Door>) // Precondition: n must be a valid array size. requires n >= 0 // Postcondition: doors is an array, which is not an alias for any other // object, with a length of n, all of whose elements are Closed. The "fresh" // (non-alias) condition is needed to allow doors to be modified by the // remaining code. ensures doors != null && fresh(doors) && doors.Length == n ensures forall j :: 0 <= j < doors.Length ==> doors[j] == Closed;{ doors := new Door[n]; var i := 0; // Invariant: i is always a valid index inside the loop, and all doors less // than i are Closed. These invariants are needed to ensure the second // postcondition. while i < doors.Length invariant i <= doors.Length invariant forall j :: 0 <= j < i ==> doors[j] == Closed; { doors[i] := Closed; i := i + 1; }} method Main (){ var doors := InitializeDoors(100); var pass := 1; while pass <= doors.Length { var door := pass; while door < doors.Length { doors[door] := if doors[door] == Closed then Open else Closed; door := door + pass; } pass := pass + 1; } var i := 0; while i < doors.Length { print i, " is ", if doors[i] == Closed then "closed\n" else "open\n"; i := i + 1; }}  ## Dart unoptimized main() { for (var k = 1, x = new List(101); k <= 100; k++) { for (int i = k; i <= 100; i += k) x[i] = !x[i]; if (x[k]) print("$k open");    }}

optimized version (including generating squares without multiplication)

main() {  for(int i=1,s=3;i<=100;i+=s,s+=2)    print("door $i is open");} comprehensible (not "code golf") version for a pedestrian language import 'dart:io'; final numDoors = 100;final List<bool> doorClosed = List(numDoors); String stateToString(String message) { var res = ''; for (var i = 0; i < numDoors; i++) { res += (doorClosed[i] ? 'X' : '\u2610'); } return res + " " + message;} main() { for (var i = 0; i < numDoors; i++) { doorClosed[i] = true; } stdout.writeln(stateToString("after initialization")); for (var step = 1; step <= numDoors; step++) { final start = step - 1; for (var i = start; i < numDoors; i += step) { doorClosed[i] = !doorClosed[i]; } stdout.writeln(stateToString("after toggling with step =$step"));  }}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX after initialization
☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐ after toggling with step = 1
☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X☐X after toggling with step = 2
☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XXX after toggling with step = 3
☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐XX☐X☐XX☐ after toggling with step = 4
☐XX☐X☐☐☐X☐☐X☐X☐☐☐☐☐XXX☐XXXX☐☐X☐☐XXXX☐XXX☐☐☐☐☐X☐X☐☐X☐☐☐X☐XX☐☐☐XX☐X☐☐☐X☐☐X☐X☐☐☐☐☐XXX☐XXXX☐☐X☐☐XXXX☐XXX after toggling with step = 5
☐XX☐XX☐☐X☐☐☐☐X☐☐☐X☐XXX☐☐XXX☐☐☐☐☐XXX☐☐XXX☐X☐☐☐X☐☐☐☐X☐☐XX☐XX☐X☐XX☐XX☐☐X☐☐☐☐X☐☐☐X☐XXX☐☐XXX☐☐☐☐☐XXX☐☐XXX after toggling with step = 6
☐XX☐XXX☐X☐☐☐☐☐☐☐☐X☐X☐X☐☐XXXX☐☐☐☐XX☐☐☐XXX☐☐☐☐☐X☐☐X☐X☐☐XXXXX☐X☐X☐☐XX☐☐XX☐☐☐X☐☐XX☐XXX☐XXXX☐☐☐X☐XXX☐☐☐XX after toggling with step = 7
☐XX☐XXXXX☐☐☐☐☐☐X☐X☐X☐X☐XXXXX☐☐☐XXX☐☐☐XX☐☐☐☐☐☐X☐XX☐X☐☐XX☐XX☐X☐X☐XXX☐☐XX☐X☐X☐☐XX☐☐XX☐XXXXX☐☐X☐XXXX☐☐XX after toggling with step = 8
☐XX☐XXXX☐☐☐☐☐☐☐X☐☐☐X☐X☐XXX☐X☐☐☐XXX☐X☐XX☐☐☐☐☐XX☐XX☐X☐☐☐X☐XX☐X☐XXXXX☐☐XX☐☐☐X☐☐XX☐☐☐X☐XXXXX☐XX☐XXXX☐☐☐X after toggling with step = 9
☐XX☐XXXX☐X☐☐☐☐☐X☐☐☐☐☐X☐XXX☐X☐X☐XXX☐X☐XXX☐☐☐☐XX☐XXXX☐☐☐X☐XX☐☐☐XXXXX☐☐X☐☐☐☐X☐☐XX☐X☐X☐XXXXX☐☐X☐XXXX☐☐☐☐ after toggling with step = 10
☐XX☐XXXX☐XX☐☐☐☐X☐☐☐☐☐☐☐XXX☐X☐X☐X☐X☐X☐XXX☐☐☐XXX☐XXXX☐☐☐☐☐XX☐☐☐XXXX☐☐☐X☐☐☐☐X☐☐☐X☐X☐X☐XXXX☐☐☐X☐XXXX☐☐X☐ after toggling with step = 11
☐XX☐XXXX☐XXX☐☐☐X☐☐☐☐☐☐☐☐XX☐X☐X☐X☐X☐☐☐XXX☐☐☐XXX☐☐XXX☐☐☐☐☐XX☐X☐XXXX☐☐☐X☐☐X☐X☐☐☐X☐X☐X☐☐XXX☐☐☐X☐XXX☐☐☐X☐ after toggling with step = 12
☐XX☐XXXX☐XXXX☐☐X☐☐☐☐☐☐☐☐X☐☐X☐X☐X☐X☐☐☐X☐X☐☐☐XXX☐☐XXXX☐☐☐☐XX☐X☐XXX☐☐☐☐X☐☐X☐X☐☐☐☐☐X☐X☐☐XXX☐☐☐☐☐XXX☐☐☐X☐ after toggling with step = 13
☐XX☐XXXX☐XXXXX☐X☐☐☐☐☐☐☐☐X☐☐☐☐X☐X☐X☐☐☐X☐X☐X☐XXX☐☐XXXX☐☐☐XXX☐X☐XXX☐☐☐☐XX☐X☐X☐☐☐☐☐X☐X☐XXXX☐☐☐☐☐XXX☐☐XX☐ after toggling with step = 14
☐XX☐XXXX☐XXXXXXX☐☐☐☐☐☐☐☐X☐☐☐☐☐☐X☐X☐☐☐X☐X☐X☐X☐X☐☐XXXX☐☐☐XXX☐☐☐XXX☐☐☐☐XX☐X☐XX☐☐☐☐X☐X☐XXXX☐☐X☐☐XXX☐☐XX☐ after toggling with step = 15
☐XX☐XXXX☐XXXXXX☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐X☐☐☐X☐X☐X☐X☐X☐XXXXX☐☐☐XXX☐☐☐XX☐☐☐☐☐XX☐X☐XX☐☐☐☐☐☐X☐XXXX☐☐X☐☐XXXX☐XX☐ after toggling with step = 16
☐XX☐XXXX☐XXXXXX☐X☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐X☐X☐X☐X☐XXX☐X☐☐☐XXX☐☐☐XX☐☐☐☐XXX☐X☐XX☐☐☐☐☐☐X☐X☐XX☐☐X☐☐XXXX☐XX☐ after toggling with step = 17
☐XX☐XXXX☐XXXXXX☐XX☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐X☐X☐X☐X☐X☐X☐XXX☐X☐X☐XXX☐☐☐XX☐☐☐☐XXX☐☐☐XX☐☐☐☐☐☐X☐X☐XX☐☐☐☐☐XXXX☐XX☐ after toggling with step = 18
☐XX☐XXXX☐XXXXXX☐XXX☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐X☐☐☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐☐☐XX☐☐☐☐XXX☐☐☐XXX☐☐☐☐☐X☐X☐XX☐☐☐☐☐XX☐X☐XX☐ after toggling with step = 19
☐XX☐XXXX☐XXXXXX☐XXXX☐☐☐☐X☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐XX☐☐☐☐XXX☐☐☐XXX☐☐☐X☐X☐X☐XX☐☐☐☐☐XX☐X☐XXX after toggling with step = 20
☐XX☐XXXX☐XXXXXX☐XXXXX☐☐☐X☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐☐☐☐☐XXX☐☐☐XXX☐☐☐X☐X☐☐☐XX☐☐☐☐☐XX☐X☐XXX after toggling with step = 21
☐XX☐XXXX☐XXXXXX☐XXXXXX☐☐X☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐X☐XXX☐X☐X☐X☐X☐X☐X☐☐☐X☐XXX☐☐☐XXX☐☐☐X☐X☐☐☐XXX☐☐☐☐XX☐X☐XXX after toggling with step = 22
☐XX☐XXXX☐XXXXXX☐XXXXXXX☐X☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐XXX☐X☐X☐X☐X☐X☐X☐☐☐X☐X☐X☐☐☐XXX☐☐☐X☐X☐☐☐XXX☐☐☐XXX☐X☐XXX after toggling with step = 23
☐XX☐XXXX☐XXXXXX☐XXXXXXXXX☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐XX☐X☐X☐X☐X☐X☐X☐☐☐X☐X☐X☐X☐XXX☐☐☐X☐X☐☐☐XXX☐☐☐XXX☐☐☐XXX after toggling with step = 24
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐X☐X☐X☐X☐X☐X☐☐☐X☐X☐X☐X☐X☐X☐☐☐X☐X☐☐☐XXX☐☐☐XXX☐☐☐XX☐ after toggling with step = 25
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐X☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐X☐X☐X☐X☐X☐☐☐X☐X☐X☐X☐X☐X☐X☐X☐X☐☐☐XXX☐☐☐XXX☐☐☐XX☐ after toggling with step = 26
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XX☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐X☐X☐X☐X☐☐☐X☐X☐X☐X☐X☐X☐X☐XXX☐☐☐XXX☐☐☐XXX☐☐☐XX☐ after toggling with step = 27
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXX☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐X☐X☐X☐☐☐X☐X☐X☐X☐X☐X☐X☐XXX☐X☐XXX☐☐☐XXX☐☐☐XX☐ after toggling with step = 28
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXX☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐X☐X☐☐☐X☐X☐X☐X☐X☐X☐X☐XXX☐X☐X☐X☐☐☐XXX☐☐☐XX☐ after toggling with step = 29
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXX☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐X☐X☐X☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐XXX☐☐☐XX☐ after toggling with step = 30
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXX☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐X☐X☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐☐☐XX☐ after toggling with step = 31
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXX☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐X☐X☐X☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐XX☐ after toggling with step = 32
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXX☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐X☐X☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 33
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐X☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 34
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐X☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 35
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐X☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 36
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐X☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 37
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XX☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐X☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 38
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXX☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐XXX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 39
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXX☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐XX☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 40
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXX☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐X☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 41
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXX☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐X☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 42
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXX☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐X☐X☐X☐X☐X☐X☐☐ after toggling with step = 43
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXX☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐X☐X☐X☐X☐X☐☐ after toggling with step = 44
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXX☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐X☐X☐X☐X☐☐ after toggling with step = 45
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXX☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐X☐X☐X☐☐ after toggling with step = 46
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐X☐☐ after toggling with step = 47
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐ after toggling with step = 48
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐ after toggling with step = 49
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 50
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XX☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 51
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXX☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 52
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXX☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 53
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXX☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 54
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXX☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 55
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXX☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 56
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXX☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 57
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXX☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 58
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXX☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 59
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXX☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 60
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXX☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 61
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 62
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 63
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 64
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 65
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XX☐☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 66
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXX☐☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 67
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXX☐☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 68
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXX☐☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 69
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXX☐☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 70
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXX☐☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 71
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXX☐☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 72
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXX☐☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 73
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXX☐☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 74
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXX☐☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 75
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXX☐☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 76
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXX☐☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 77
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXX☐☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 78
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 79
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 80
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 81
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐X☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 82
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 83
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 84
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXX☐☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 85
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXX☐☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 86
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXX☐☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 87
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXX☐☐☐☐☐☐☐☐☐☐☐X after toggling with step = 88
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXX☐☐☐☐☐☐☐☐☐☐X after toggling with step = 89
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXX☐☐☐☐☐☐☐☐☐X after toggling with step = 90
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXX☐☐☐☐☐☐☐☐X after toggling with step = 91
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXX☐☐☐☐☐☐☐X after toggling with step = 92
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXX☐☐☐☐☐☐X after toggling with step = 93
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXX☐☐☐☐☐X after toggling with step = 94
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXXX☐☐☐☐X after toggling with step = 95
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXXXX☐☐☐X after toggling with step = 96
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐☐X after toggling with step = 97
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXXX☐X after toggling with step = 98
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXXXXX after toggling with step = 99
☐XX☐XXXX☐XXXXXX☐XXXXXXXX☐XXXXXXXXXX☐XXXXXXXXXXXX☐XXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXX☐XXXXXXXXXXXXXXXXXX☐ after toggling with step = 100

## Dc

Unoptimized:

Works with: GNU dc version 1.3.95
 ## NB: This code uses the dc command "r" via register "r".##     You may comment out the unwanted version.[SxSyLxLy]sr    # this should work with every "dc"[r]sr           # GNU dc can exchange top 2 stack values by "r"## Now use "lrx" instead of "r" ... 0k              # we work without decimal places[q]sq           # useful e.g. as loop termination ## (x)(y)>R  ==  if (y)>(x) eval R## isle         x y --> (x <= y)[    [1q]S. [ !<. 0 ]x s.L.]sl## l: isle [    100 llx]sL## L: isle100 ## for  initcode condcode incrcode body##                         [    [q]S. 4:. 3:. 2:. 1:.  1;.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x Os.L.o]sf## f: for##---------------------------------------------------------------------------- ##      for( i=1 ; i<=100 ; ++i ) {##          door[i] = 0;##      }#[init ...]P []ps-[1si] [li lLx] [li1+si] [    li 0:d]lfx ##      for( s=1 ; s<=100 ; ++s ) {##          for( i=s ; i<=100 ; i+=s ) {##              door[i] = 1 - door[i]##          }##      }[1ss] [ls lLx] [ls1+ss] [    #[step ]P lsn [ ...]ps-    [lssi] [li lLx] [lils+si] [        1 li;d - li:d    ]lfx]lfx ##      long output:##          for( i=1 ; i<=100 ; ++i ) {##              print "door #", i, " is ", (door[i] ? "open" : "closed")), NL##          }[    [1si] [li lLx] [li1+si] [        [door #]P        li n        [ is ]P            [closed]            [open]        li;d 0=r lrx s- n        [.]ps-    ]lfx] ##      terse output:##          for( i=1 ; i<=100 ; ++i ) {##              if( door[i] ) {##                  print i##              }##              print NL##          }[    [1si] [li lLx] [li1+si] [        [] [ [ ]n lin ]        li;d 0=r lrx s- x    ]lfx    []ps-] lrx             # comment out for the long output versions- x#[stack rest...]P []ps- f 

Output:

 1 4 9 16 25 36 49 64 81 100


## DCL

 $! doors.com$! Excecute by running @doors at prompt.$square = 1$ incr = 3$count2 = 0$ d = 1$LOOP2:$       count2 = count2 + 1$IF (d .NE. square)$               THEN WRITE SYS$OUTPUT "door ''d' is closed"$       ELSE WRITE SYS$OUTPUT "door ''d' is open"$               square = incr + square$incr = incr + 2$       ENDIF$d = d + 1$       IF (count2 .LT. 100) THEN GOTO LOOP2 

See Pascal

## DUP

100[$][0^:1-]# {initialize doors}%[s;[$101<][$$;~\:s;+]#%]d: {function d, switch door state function}1s:[s;101<][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time}1[101<][$$.' ,;['o,'p,'e,'n,10,]['c,'l,'o,'s,'e,'d,10,]?1+]#  {loop through doors, print door number and state}

Result:

1 open2 closed3 closed4 open5 closed6 closed7 closed8 closed9 open10 closed11 closed12 closed...94 closed95 closed96 closed97 closed98 closed99 closed100 open

Compare this solution to the FALSE solution of this problem.

## DWScript

Unoptimized

var doors : array [1..100] of Boolean;var i, j : Integer; for i := 1 to 100 do   for j := i to 100 do      if (j mod i) = 0 then         doors[j] := not doors[j];F for i := 1 to 100 do   if doors[i] then      PrintLn('Door '+IntToStr(i)+' is open');

## Dyalect

Outputs only open doors to save up space:

var doors = Array.empty(100, false) for p in 0..99 {    for d in 0..99 {        if (d + 1) % (p + 1) == 0 {            doors[d] = !doors[d];        }    }} for d in doors.indices() when doors[d] {    print("Door $$d+1): Open")} Output: Door 1: Open Door 4: Open Door 9: Open Door 16: Open Door 25: Open Door 36: Open Door 49: Open Door 64: Open Door 81: Open Door 100: Open ## Dylan Unoptimized define method doors() let doors = make(<array>, fill: #f, size: 100); for (x from 0 below 100) for (y from x below 100 by x + 1) doors[y] := ~doors[y] end end; for (x from 1 to 100) if (doors[x - 1]) format-out("door %d open\n", x) end endend ## Déjà Vu local :open-doors [ rep 101 false ] for i range 1 100: local :j i while <= j 100: set-to open-doors j not open-doors! j set :j + j i !print\ "Open doors: "for i range 1 100: if open-doors! i: !print\( to-str i " " ) Output: Open doors: 1 4 9 16 25 36 49 64 81 100  ## E Graphical Works with: E-on-Java This version animates the changes of the doors (as checkboxes). #!/usr/bin/env rune var toggles := []var gets := [] # Set up GUI (and data model)def frame := <swing:makeJFrame>("100 doors")frame.getContentPane().setLayout(<awt:makeGridLayout>(10, 10))for i in 1..100 { def component := <import:javax.swing.makeJCheckBox>(E.toString(i)) toggles with= fn { component.setSelected(!component.isSelected()) } gets with= fn { component.isSelected() } frame.getContentPane().add(component)} # Set up termination conditiondef doneframe.addWindowListener(def _ { to windowClosing(event) { bind done := true } match _ {}}) # Open and close doorsdef loop(step, i) { toggles[i] <- () def next := i + step timer.whenPast(timer.now() + 10, fn { if (next >= 100) { if (step >= 100) { # Done. } else { loop <- (step + 1, step) } } else { loop <- (step, i + step) } })}loop(1, 0) frame.pack()frame.show()interp.waitAtTop(done) ## EasyLang intvarslen d[] 101for p = 1 to 100 i = p while i <= 100 d[i] = 1 - d[i] i += p ..for i = 1 to 100 if d[i] = 1 print i .. ## EchoLisp The result is obviously the same in we run the process backwards. So, we check the state of each door during the 100-th step (opening/closing every door)  ; initial state = closed = #f(define doors (make-vector 101 #f)); run pass 100 to 1(for* ((pass (in-range 100 0 -1)) (door (in-range 0 101 pass))) (when (and (vector-set! doors door (not (vector-ref doors door))) (= pass 1)) (writeln door "is open"))) 1 "is open" 4 "is open" 9 "is open" 16 "is open" 25 "is open" 36 "is open" 49 "is open" 64 "is open" 81 "is open" 100 "is open"  ## ECL optimized version  Doors := RECORD UNSIGNED1 DoorNumber; STRING6 State;END; AllDoors := DATASET([{0,0}],Doors); Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM SELF.DoorNumber := Cnt; SELF.State := IF((CNT * 10) % (SQRT(CNT)*10)<>0,'Closed','Opened');END; OpenDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER)); OpenDoors;  unoptimized version - demonstrating LOOP  Doors := RECORD UNSIGNED1 DoorNumber; STRING6 State;END; AllDoors := DATASET([{0,'0'}],Doors); //first build the 100 doors Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM SELF.DoorNumber := Cnt; SELF.State := 'Closed';END; ClosedDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER)); //now iterate through them and use door logic loopBody(DATASET(Doors) ds, UNSIGNED4 c) := PROJECT(ds, //ds=original input TRANSFORM(Doors, SELF.State := CASE((COUNTER % c) * 100, 0 => IF(LEFT.STATE = 'Opened','Closed','Opened') ,LEFT.STATE); SELF.DoorNumber := COUNTER; //PROJECT COUNTER )); g1 := LOOP(ClosedDoors,100,loopBody(ROWS(LEFT),COUNTER)); OUTPUT(g1);  unoptimized version - using ITERATE This is a bit more efficient than the LOOP version  DoorSet := DATASET(100,TRANSFORM({UNSIGNED1 DoorState},SELF.DoorState := 1));SetDoors := SET(DoorSet,DoorState); Doors := RECORD UNSIGNED1 Pass; SET OF UNSIGNED1 DoorSet;END; StartDoors := DATASET(100,TRANSFORM(Doors,SELF.Pass := COUNTER,SELF.DoorSet := SetDoors)); Doors XF(Doors L, Doors R) := TRANSFORM ds := DATASET(L.DoorSet,{UNSIGNED1 DoorState}); NextDoorSet := PROJECT(ds, TRANSFORM({UNSIGNED1 DoorState}, SELF.DoorState := CASE((COUNTER % R.Pass) * 100, 0 => IF(LEFT.DoorState = 1,0,1), LEFT.DoorState))); SELF.DoorSet := IF(L.Pass=0,R.DoorSet,SET(NextDoorSet,DoorState)); SELF.Pass := R.Pass END; Res := DATASET(ITERATE(StartDoors,XF(LEFT,RIGHT)).DoorSet,{UNSIGNED1 DoorState});PROJECT(Res,TRANSFORM({STRING20 txt},SELF.Txt := 'Door ' + COUNTER + ' is ' + IF(LEFT.DoorState=1,'Open','Closed')));  ## EDSAC order code Since there are only 100 doors, we'll keep things simple and use a whole EDSAC location for each door. A single bit would be enough, but that would make the code much longer. The program works through the array of doors by modifying its own orders (instructions). This would be considered bad practice today, but was quite usual on the EDSAC.  [Hundred doors problem from Rosetta Code website][EDSAC program, Initial Orders 2] [Library subroutine M3. Prints header and is then overwritten.Here, the last character sets the teleprinter to figures.] [email protected]@E8FEZPF @&*[email protected]&# ..PZ [blank tape, needed to mark end of header text] [Library subroutine P6. Prints strictly positive integer.32 locations; working locations 1, 4, 5] T56K [define load address for subroutine] [email protected]@[email protected]@[email protected] [email protected] [email protected]@[email protected]@J995FJF!F T88K [define load address for main program] GK [set @ (theta) for relative addresses] [The 100 doors are at locations 200..299.Doors are numbered 0..99 internally, and 1..100 for output.The base address and the number of doors can be varied.The value of a door is 0 if open, negative if closed.] [Constants. Program also uses order 'P 1 F' which is permanently at absolute address 2.]  P200F [address of door #0]  P100F [number of doors, as an address]  UF [makes S order from T, since 'S' = 'T' + 'U']  MF [makes A order from T, since 'A' = 'T' + 'M']  V2047D [all 1's for "closed" (any negative value will do)]  &F [line feed]  @F [carriage return]  K4096F [teleprinter null[ [Variables]  PF [pass number; step when toggling doors]  PF [door number, as address, 0-based]  PF [order referring to door 0] [Enter with acc = 0] [Part 1 : close all the doors]  [email protected] [pass := 0 (used in part 2)] [email protected] [door number := 0] [email protected] [load 'T F' order] [email protected] [add base address] [email protected] [store T order for door #0]  TF [clear acc; also serves as constant] [email protected] [load door number] [email protected] [make T order] [email protected] [plant in code] [email protected] [load value for "closed"]  TF [store in current door] [email protected] [load door number] A2F [add 1] [email protected] [update door number] [email protected] [done all doors yet?] [email protected] [if not, loop back] [Part 2 : 100 passes, toggling the doors]  TF [clear acc] [email protected] [load pass number] A2F [add 1] [email protected] [save updated pass number] S2F [make -1] [email protected] [door number := -1] [email protected] [add pass number to get first door toggled on this pass] [email protected] [gone beyond end?] [email protected] [if so, move on to part 3]  [email protected] [restore acc after test] [email protected] [store current door number] [email protected] [make T order to load status] [email protected] [plant T order for first door in pass] [email protected] [convert to S order] [email protected] [plant S order] [email protected] [load value for "closed"]  SF [subtract status; toggles status]  TF [update status] [email protected] [load door number just toggled] [email protected] [add pass number to get next door in pass] [email protected] [gone beyond end?] [email protected] [no, loop to do next door] [email protected] [yes, loop to do next pass] [Part 3 : Print list of open doors. Header has set teleprinter to figures.]  TF [clear acc] [email protected] [door nr := 0] [email protected] [T order for door 0] [email protected] [convert to A order] [email protected]  TF [email protected] [load door number] [email protected] [make A order to load value] [email protected] [plant in next order]  AF [acc := 0 if open, < 0 if closed] [email protected] [skip if closed] [email protected] [door number as address] A2F [add 1 for 1-based output] RD [shift 1 right, address --> integer] TF [store integer at 0 for printing]  [email protected] [for return from subroutine] G56F [call subroutine to print door number] [email protected] [followed by CRLF] [email protected]  TF [clear acc] [email protected] [load door number] A2F [add 1] [email protected] [update door number] [email protected] [done all doors yet?] [email protected] [if not, loop back]  [email protected] [output null to flush teleprinter buffer] ZF [stop] E11Z [define relative start address] PF  Output: THE OPEN DOORS ARE 1 4 9 16 25 36 49 64 81 100  ## Eero  #import <Foundation/Foundation.h> int main() square := 1, increment = 3 for int door in 1 .. 100 printf("door #%d", door) if door == square puts(" is open.") square += increment increment += 2 else puts(" is closed.") return 0  ## Egel  import "prelude.eg" using Systemusing List data open, closed def toggle = [ open N -> closed N | closed N -> open N ] def doors = [ N -> map [ N -> closed N ] (fromto 1 N) ] def toggleK = [ K nil -> nil | K (cons (D N) DD) -> let DOOR = if (N%K) == 0 then toggle (D N) else D N in cons DOOR (toggleK K DD) ] def toggleEvery = [ nil DOORS -> DOORS | (cons K KK) DOORS -> toggleEvery KK (toggleK K DOORS) ] def run = [ N -> toggleEvery (fromto 1 N) (doors N) ] def main = run 100  ## EGL  program OneHundredDoors function main() doors boolean[] = new boolean; n int = 100; for (i int from 1 to n) for (j int from i to n by i) doors[j] = !doors[j]; end end for (i int from 1 to n) if (doors[i]) SysLib.writeStdout( "Door " + i + " is open" ); end end end end  ## Eiffel This is my first RosettaCode submission, as well as a foray into Eiffel for myself. I've tried to adhere to the description of the problem statement, as well as showcase a few Eiffelisms shown in the documentation. The replacement code below took the original code and has made improvements in some ways, such as: 1. Removal of "magic" many magic numbers and strings. 2. Refactor of various code blocks to routines (commands and queries with good CQS). 3. Utilization/Demonstration of full, secret, and selective feature exporting. 4. Utilization/Demonstration of constants as expanded type constants and once-functions. 5. Utilization/Demonstration of static-references (e.g. {APPLICATION}.min_door_count). 6. Utilization/Demonstration of "like" keyword type anchoring (e.g. a_index_address: like {DOOR}.address). 7. Utilization/Demonstration of semi-strict logical implication (e.g. consistency: is_open implies not Is_closed). 8. Utilization/Demonstration of contracts, including require, ensure, and class invariant. 9. Utilization/Demonstration of agent and do_all' call on ITERABLE type. 10. Utilization/Demonstration of various forms of across including "loop" and "all". ... as well as other Eiffel-ism's and some coding standards/best-practices. file: application.e note description: "100 Doors problem" date: "08-JUL-2015" revision: "1.1" class APPLICATION create make feature {NONE} -- Initialization make -- Main application routine. do initialize_closed_doors toggle_doors output_door_states end feature -- Access doors: ARRAYED_LIST [DOOR] -- A set of doors (self-initialized to capacity of max_door_count'). attribute create Result.make (max_door_count) end feature -- Basic Operations initialize_closed_doors -- Initialize all doors'. do across min_door_count |..| max_door_count as ic_address_list loop doors.extend (create {DOOR}.make_closed (ic_address_list.item)) end ensure has_all_closed_doors: across doors as ic_doors_list all not ic_doors_list.item.is_open end end toggle_doors -- Toggle all doors'. do across min_door_count |..| max_door_count as ic_addresses_list loop across doors as ic_doors_list loop if is_door_to_toggle (ic_doors_list.item.address, ic_addresses_list.item) then ic_doors_list.item.toggle_door end end end end output_door_states -- Output the state of all doors'. do doors.do_all (agent door_state_out) end feature -- Status Report is_door_to_toggle (a_door_address, a_index_address: like {DOOR}.address): BOOLEAN -- Is the door at a_door_address' needing to be toggled, when compared to a_index_address'? do Result := a_door_address \\ a_index_address = 0 ensure only_modulus_zero: Result = (a_door_address \\ a_index_address = 0) end feature -- Outputs door_state_out (a_door: DOOR) -- Output the state of a_door'. do print ("Door " + a_door.address.out + " is ") if a_door.is_open then print ("open.") else print ("closed.") end io.new_line end feature {DOOR} -- Constants min_door_count: INTEGER = 1 -- Minimum number of doors. max_door_count: INTEGER = 100 -- Maximum number of doors. end file: door.e note description: "A door with an address and an open or closed state." date: "08-JUL-2015" revision: "1.1" class DOOR create make_closed, make feature {NONE} -- initialization make_closed (a_address: INTEGER) -- Initialize Current {DOOR} at a_address' and state of Is_closed'. require positive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count do make (a_address, Is_closed) ensure closed: is_open = Is_closed end make (a_address: INTEGER; a_status: BOOLEAN) -- Initialize Current {DOOR} with a_address' and a_status', denoting position and is_open' or Is_closed'. require positive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count do address := a_address is_open := a_status ensure address_set: address = a_address status_set: is_open = a_status end feature -- access address: INTEGER -- address' of Current {DOOR}. is_open: BOOLEAN assign set_open -- is_open' (or not) status of Current {DOOR}. feature -- Setters set_open (a_status: BOOLEAN) -- Set status' with a_status' do is_open := a_status ensure open_updated: is_open = a_status end feature {APPLICATION} -- Basic Operations toggle_door -- Toggle Current {DOOR} from is_open' to not is_open'. do is_open := not is_open ensure toggled: is_open /= old is_open end feature {NONE} -- Implementation: Constants Is_closed: BOOLEAN = False -- State of being not is_open'. Min_door_count: INTEGER = 1 -- Minimum door count. invariant one_or_more: address >= 1 consistency: is_open implies not Is_closed end ## Ela Standard Approach open generic type Door = Open | Closed deriving Show gate [] _ = []gate (x::xs) (y::ys) | x == y = Open :: gate xs ys | else = Closed :: gate xs ys run n = gate [1..n] [& k*k \\ k <- [1..]] Alternate Approach open listrun n = takeWhile (<n) [& k*k \\ k <- [1..]] ## Elena ELENA 4.0 : import system'routines;import extensions; public program(){ var Doors := Array.allocate(100).populate:(n=>false); for(int i := 0, i < 100, i := i + 1) { for(int j := i, j < 100, j := j + i + 1) { Doors[j] := Doors[j].Inverted } }; for(int i := 0, i < 100, i := i + 1) { console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) }; console.readChar()} ## Elixir defmodule HundredDoors do def doors(n \\ 100) do List.duplicate(false, n) end def toggle(doors, n) do List.update_at(doors, n, &(!&1)) end def toggle_every(doors, n) do Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end ) endend # unoptimizedfinal_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end) open_doors = Enum.with_index(final_state) |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end) IO.puts "All doors are closed except these: #{inspect open_doors}" # optimized final_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end) open_doors = Enum.with_index(final_state) |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end) IO.puts "All doors are closed except these: #{inspect open_doors}" Output: All doors are closed except these: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ## Elm -- Unoptimizedimport List exposing (indexedMap, foldl, repeat, range)import Html exposing (text)import Debug exposing (toString) type Door = Open | Closed toggle d = if d == Open then Closed else Open toggleEvery : Int -> List Door -> List DoortoggleEvery k doors = indexedMap (\i door -> if modBy k (i+1) == 0 then toggle door else door) doors n = 100 main = text (toString (foldl toggleEvery (repeat n Closed) (range 1 n)))  ## Emacs Lisp Unoptimized (defun create-doors () "Returns a list of closed doors Each door only has two status: open or closed.If a door is closed it has the value 0, if it's open it has the value 1." (let ((return_value '(0)) ;; There is already a door in the return_value, so k starts at 1 ;; otherwise we would need to compare k against 99 and not 100 in ;; the while loop (k 1)) (while (< k 100) (setq return_value (cons 0 return_value)) (setq k (+ 1 k))) return_value)) (defun toggle-single-door (doors) "Toggle the stat of the door at the car' position of the DOORS list DOORS is a list of integers with either the value 0 or 1 and it representsa row of doors. Returns a list where the car' of the list has it's value toggled (if openit becomes closed, if closed it becomes open)." (if (= (car doors) 1) (cons 0 (cdr doors)) (cons 1 (cdr doors)))) (defun toggle-doors (doors step original-step) "Step through all elements of the doors' list and toggle a door when step is 1 DOORS is a list of integers with either the value 0 or 1 and it representsa row of doors.STEP is the number of doors we still need to transverse before we arriveat a door that has to be toggled.ORIGINAL-STEP is the value of the argument step when this function iscalled for the first time. Returns a list of doors" (cond ((null doors) '()) ((= step 1) (cons (car (toggle-single-door doors)) (toggle-doors (cdr doors) original-step original-step))) (t (cons (car doors) (toggle-doors (cdr doors) (- step 1) original-step))))) (defun main-program () "The main loop for the program" (let ((doors_list (create-doors)) (k 1) ;; We need to define max-specpdl-size and max-specpdl-size to big ;; numbers otherwise the loop reaches the max recursion depth and ;; throws an error. ;; If you want more information about these variables, press Ctrl ;; and h at the same time and then press v and then type the name ;; of the variable that you want to read the documentation. (max-specpdl-size 5000) (max-lisp-eval-depth 2000)) (while (< k 101) (setq doors_list (toggle-doors doors_list k k)) (setq k (+ 1 k))) doors_list)) (defun print-doors (doors) "This function prints the values of the doors into the current buffer. DOORS is a list of integers with either the value 0 or 1 and it representsa row of doors." ;; As in the main-program function, we need to set the variable ;; max-lisp-eval-depth to a big number so it doesn't reach max recursion ;; depth. (let ((max-lisp-eval-depth 5000)) (unless (null doors) (insert (int-to-string (car doors))) (print-doors (cdr doors))))) ;; Returns a list with the final solution(main-program) ;; Print the final solution on the buffer(print-doors (main-program)) ## Erlang non-optimized  -module(hundoors). -export([go/0]). toggle(closed) -> open;toggle(open) -> closed. go() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1).go([], L, N, _I) when N =:= 101 -> lists:reverse(L);go([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1);go([H|T], L, N, I) -> H2 = case I rem N of 0 -> toggle(H); _ -> H end, go(T, [H2|L], N, I + 1).  optimized doors() -> F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end, Out = fun(X, true) -> io:format("Door ~p: open~n",[X]); (X, false)-> io:format("Door ~p: close~n",[X]) end, [Out(X,F(X)) || X <- lists:seq(1,100)]. ## ERRE  ! "100 Doors" program for ERRE LANGUAGE! Author: Claudio Larini! Date: 21-Nov-2014!! PC Unoptimized version translated from a QB version PROGRAM 100DOORS !INTEGER CONST N=100 DIM DOOR[N] BEGIN FOR STRIDE=1 TO N DO FOR INDEX=STRIDE TO N STEP STRIDE DO DOOR[INDEX]=NOT(DOOR[INDEX]) END FOREND FOR PRINT("Open doors:";)FOR INDEX=1 TO N DO IF DOOR[INDEX] THEN PRINT(INDEX;) END IFEND FORPRINT END PROGRAM  ## Euler Math Toolbox  >function Doors () ... doors:=zeros(1,100); for i=1 to 100 for j=i to 100 step i doors[j]=!doors[j]; end; end; return doorsendfunction>nonzeros(Doors()) [ 1 4 9 16 25 36 49 64 81 100 ]  ## Euphoria unoptimised -- doors.exinclude std/console.esequence doorsdoors = repeat( 0, 100 ) -- 1 to 100, initialised to false for pass = 1 to 100 do for door = pass to 100 by pass do --printf( 1, "%d", doors[door] ) --printf( 1, "%d", not doors[door] ) doors[door] = not doors[door] end forend for sequence oc for i = 1 to 100 do if doors[i] then oc = "open" else oc = "closed" end if printf( 1, "door %d is %s\n", { i, oc } )end for  ## Excel Note: The use of Auto Fill saves a lot of time when entering this code. One can refer to Excel help pages to learn about Auto Fill features. Create a labelling column (A) and row (1) labelling the number of the door (column A, labelling starts in row 2 with a "1" and continues counting up to "100" in row 101) and the number of the pass (row 1, labelling starts in column B with a "0" and continues counting up to "100" in column CX). Additonally, you can label cell A1 as "Door/Pass" or so. Closed doors are represented by zeroes ("0"), open doors are represented by ones ("1"). To represent the initial condition fill rows 2 to 101 in column B (pass "0") with zeroes. Starting in column C, row 2, you enter code as shown in the examples below. The examples show the code to be entered in cells C2, C3, and D2. Continue to write code for the rest of the 4245 data cells, accordingly. Excel Auto Fill feature is best used for this. Cell C2:  =IF(A2/C1=INT(A2/C1),IF(B2=0,1,IF(B2=1,0)),B2)  Cell C3:  =IF(A3/C1=INT(A3/C1),IF(B3=0,1,IF(B3=1,0)),B3)  Cell D2:  =IF(A2/D1=INT(A2/D1),IF(C2=0,1,IF(C2=1,0)),C2)  The last column (column CX, labelled "100") shows a "1" for each door (labelled by the rows in column A) that is open after the 100th pass. It shows a "1" for the following doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100. ## F# Requires #light in versions of F# prior to 2010 beta. let answerDoors = let ToggleNth n (lst:bool array) = // Toggle every n'th door [(n-1) .. n .. 99] // For each appropriate door |> Seq.iter (fun i -> lst.[i] <- not lst.[i]) // toggle it let doors = Array.create 100 false // Initialize all doors to closed Seq.iter (fun n -> ToggleNth n doors) [1..100] // toggle the appropriate doors for each pass doors // Initialize all doors to closed  Unoptimized / functional  let modifier doors skip = let rec modifierInner doors skip counter = match doors with | [] -> [] //base case: end of hall | first::rest when counter >= skip -> //case: reached door marked for change not first::(modifierInner rest skip 0) // open or close that door | first::rest -> //case: reached door to skip first::(modifierInner rest skip (counter+1)) // skip it modifierInner doors skip 0 //Initial state for walkthrough let answerDoors doors = let rec modifyDoors skipRange doors modifier = //fold each door result to the next with List.fold modifier doors skipRange //with an increasing skip modifyDoors [0..99] doors modifier //Initial starting state let initDoors = Array.create 100 false |> Array.toList //Initialize all doors to closed (false) answerDoors initDoors |> printfn "%A" //print answer (false is closed door)  Tail-Recursive Optimized/Functional  let modifier doors skip = let rec modifier' doors skip counter result = match doors with | [] -> result |> List.rev //base case: end of hall | first::rest when counter >= skip -> //case: reached door marked for change modifier' rest skip 0 ((not first)::result) // open or close that door | first::rest -> //case: reached door to skip modifier' rest skip (counter+1) (first::result) // skip it modifier' doors skip 0 [] //Initial state for walkthrough  Following is the solution using perfect squares. The coercions in PerfectSquare are, I believe, slightly different in versions prior to 2010 beta and, again, #light is required in those versions. open Systemlet answer2 = let PerfectSquare n = let sqrt = int(Math.Sqrt(float n)) n = sqrt * sqrt [| for i in 1..100 do yield PerfectSquare i |] Simple single line solution using nothing but List  [1..100] |> List.fold (fun doors pass->List.mapi (fun i x->if ((i + 1) % pass)=0 then not x else x) doors) (List.init 100 (fun _->false))  ## Factor Unoptimized USING: bit-arrays formatting fry kernel math math.rangessequences ;IN: rosetta.doors CONSTANT: number-of-doors 100 : multiples ( n -- range ) 0 number-of-doors rot <range> ; : toggle-multiples ( n doors -- ) [ multiples ] dip '[ _ [ not ] change-nth ] each ; : toggle-all-multiples ( doors -- ) [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each ; : print-doors ( doors -- ) [ swap "open" "closed" ? "Door %d is %s\n" printf ] each-index ; : main ( -- ) number-of-doors 1 + <bit-array> [ toggle-all-multiples ] [ print-doors ] bi ; main Optimized  USING: formatting math math.primes.factors math.ranges sequences ;IN: rosetta-doors2 : main ( -- ) 100 [1,b] [ divisors length odd? ] filter "Open %[%d, %]\n" printf ;  ## Falcon Unoptimized code doors = arrayBuffer( 101, false ) for pass in [ 0 : doors.len() ] for door in [ 0 : doors.len() : pass+1 ] doors[ door ] = not doors[ door ] endend for door in [ 1 : doors.len() ] // Show Output > "Door ", door, " is: ", ( doors[ door ] ) ? "open" : "closed"end  Optimized code  for door in [ 1 : 101 ]: > "Door ", door, " is: ", fract( door ** 0.5 ) ? "closed" : "open" ## FALSE 100[][0 1ø:1-]# {initialize doors}%[s;[101\>][;~\:s;+]#%]d: {function d, switch door state function}1s:[s;101\>][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time}1[101\>][." ";["open"]?~["closed"]?1+]# {loop through doors, print door number and state} Result: 1 open2 closed3 closed4 open5 closed6 closed7 closed8 closed9 open10 closed...98 closed99 closed100 open Compare this solution to the DUP solution of this problem. ## Fantom Unoptimized  states := (1..100).toList 100.times |i| { states = states.map |state| { state % (i+1) == 0 ? -state : +state } } echo("Open doors are " + states.findAll { it < 0 }.map { -it })  Optimized  echo("Open doors are " + (1..100).toList.findAll { it.toFloat.pow(0.5f).toInt.pow(2) == it})  ## FBSL Unoptimised #AppType Console DIM doors[], n AS INTEGER = 100 FOR DIM i = 1 TO n FOR DIM j = i TO n STEP i doors[j] = NOT doors[j] NEXTNEXT FOR i = 1 TO n IF doors[i] THEN PRINT "Door ", i, " is open"NEXT Pause Optimised (by ML) #APPTYPE CONSOLE DIM i = 0, j = 0, door = 1 WHILE INCR(i) < 101 IF i = door THEN PRINT "Door ", door, " open" INCR(door, INCR((INCR(j) << 1))) END IFWEND PAUSE ## Fish Unoptimized 1001-p01.>0101-p02.>101-g001-g+:::aa*)?v101-p03.>02-g?v1}02-p02. >05. >0}02-p02.>~~~0101-p001-g:1+001-paa*)?v02. >07.>0101-p08.>101-g::02-g?v >1+:101-paa*=?; >n" "o^ ## Forth Unoptimized : toggle ( c-addr -- ) \ toggle the byte at c-addr dup [email protected] 1 xor swap c! ; 100 1+ ( 1-based indexing ) constant ndoorscreate doors ndoors allot : init ( -- ) doors ndoors erase ; \ close all doors : pass ( n -- ) \ toggle every nth door ndoors over do doors i + toggle dup ( n ) +loop drop ; : run ( -- ) ndoors 1 do i pass loop ;: display ( -- ) \ display open doors ndoors 1 do doors i + [email protected] if i . then loop cr ; init run display Optimized : squared ( n -- n' ) dup * ;: doors ( n -- ) 1 begin 2dup squared >= while dup squared . 1+ repeat 2drop ;100 doors ## Fortran Works with: Fortran 90 unoptimized program doors implicit none integer, allocatable :: door(:) character(6), parameter :: s(0:1) = ["closed", "open "] integer :: i, n print "(A)", "Number of doors?" read *, n allocate (door(n)) door = 1 do i = 1, n door(i:n:i) = 1 - door(i:n:i) print "(A,G0,2A)", "door ", i, " is ", s(door(i)) end doend program optimized PROGRAM DOORS INTEGER, PARAMETER :: n = 100 ! Number of doors INTEGER :: i LOGICAL :: door(n) = .TRUE. ! Initially closed DO i = 1, SQRT(REAL(n)) door(i*i) = .FALSE. END DO DO i = 1, n WRITE(*,"(A,I3,A)", ADVANCE="NO") "Door ", i, " is " IF (door(i)) THEN WRITE(*,"(A)") "closed" ELSE WRITE(*,"(A)") "open" END IF END DO END PROGRAM DOORS ## Free Pascal  program OneHundredIsOpen; const DoorCount = 100; var IsOpen: array[1..DoorCount] of boolean; Door, Jump: integer; begin // Close all doors for Door := 1 to DoorCount do IsOpen[Door] := False; // Iterations for Jump := 1 to DoorCount do begin Door := Jump; repeat IsOpen[Door] := not IsOpen[Door]; Door := Door + Jump; until Door > DoorCount; end; // Show final status for Door := 1 to DoorCount do begin Write(Door, ' '); if IsOpen[Door] then WriteLn('open') else WriteLn('closed'); end; // Wait for <enter> Readln;end.  ## FreeBASIC ### Toggle ' version 27-10-2016' compile with: fbc -s console #Define max_doors 100 Dim As ULong c, n, n1, door(1 To max_doors) ' toggle, at start all doors are closed (0)' 0 = door closed, 1 = door openFor n = 1 To max_doors For n1 = n To max_doors Step n door(n1) = 1 - door(n1) NextNext ' count the doors that are open (1)Print "doors that are open nr: ";For n = 1 To max_doors If door(n) = 1 Then Print n; " "; c = c + 1 End IfNext Print : PrintPrint "There are " + Str(c) + " doors open" ' empty keyboard bufferWhile InKey <> "" : WendPrint : Print "hit any key to end program"SleepEnd Output: doors that are open nr: 1 4 9 16 25 36 49 64 81 100 There are 10 doors open ### Count ' version 27-10-2016' compile with: fbc -s console #Define max_doors 100 Dim As ULong c, n, n1, door(1 To max_doors) ' at start all doors are closed' simple add 1 each time we open or close a door' doors with odd numbers are open' doors with even numbers are closedFor n = 1 To max_doors For n1 = n To max_doors Step n door(n1) += 1 NextNext Print "doors that are open nr: ";For n = 1 To max_doors If door(n) And 1 Then Print n; " "; c = c + 1 End IfNext Print : PrintPrint "There are " + Str(c) + " doors open" ' empty keyboard bufferWhile InKey <> "" : WendPrint : Print "hit any key to end program"SleepEnd Output is the same as the first version. ### Optimized ' version 27-10-2016' compile with: fbc -s console #Define max_doors 100 Dim As ULong c, n Print "doors that are open nr: ";For n = 1 To 10 Print n * n; " "; c = c + 1Next Print : PrintPrint "There are " + Str(c) + " doors open" ' empty keyboard bufferWhile InKey <> "" : WendPrint : Print "hit any key to end program"SleepEnd Output is the same as the first version. ## friendly interactive shell Unoptimized # Set doors to empty listset doors # Initialize doors arraysfor i in (seq 100) set doors[i] 0end for i in (seq 100) set j i while test j -le 100 # Logical not on doors set doors[j] (math !doors[j]) set j (math j + i) endend # Print every doorfor i in (seq (count doors)) echo -n "i " if test doors[i] -eq 0 echo closed else echo open endend  Optimized # Set doors to empty listset doors for i in (seq 100) set doors[(math "i * i")] 1 echo -n "i " if test doors[i] -eq 1 echo open else echo closed endend ## Frink  doors = new array[, false]for pass=1 to 100 for door=pass to 100 step pass [email protected] = ! [email protected] print["Open doors: "]for door=1 to 100 if [email protected] print["door "]  ## FunL ### Unoptimized for i <- 1..100 r = foldl1( \a, b -> a xor b, [(a|i) | a <- 1..100] ) println( i + ' ' + (if r then 'open' else 'closed') ) ### Optimized import math.sqrt for i <- 1..100 println( i + ' ' + (if sqrt(i) is Integer then 'open' else 'closed') ) ## Futhark  let main(n: i32): [n]bool = loop is_open = replicate n false for i < n do let js = map (*i+1) (iota n) let flips = map (\j -> if j < n then unsafe !is_open[j] else true -- Doesn't matter. ) js in scatter is_open js flips  ## FutureBasic  include "ConsoleWindow" dim as short door, square : square = 1dim as short increment : increment = 3 for door = 1 to 100 if (door == square) print "Door"; door; " is open." square += increment increment += 2 else print "Door"; door; " is closed." end ifnext  Output: Door 1 is open. Door 2 is closed. Door 3 is closed. Door 4 is open. Door 5 is closed. Door 6 is closed. Door 7 is closed. Door 8 is closed. Door 9 is open. Door 10 is closed. Door 11 is closed. Door 12 is closed. Door 13 is closed. Door 14 is closed. Door 15 is closed. Door 16 is open. Door 17 is closed. Door 18 is closed. Door 19 is closed. Door 20 is closed. Door 21 is closed. Door 22 is closed. Door 23 is closed. Door 24 is closed. Door 25 is open. Door 26 is closed. Door 27 is closed. Door 28 is closed. Door 29 is closed. Door 30 is closed. Door 31 is closed. Door 32 is closed. Door 33 is closed. Door 34 is closed. Door 35 is closed. Door 36 is open. Door 37 is closed. Door 38 is closed. Door 39 is closed. Door 40 is closed. Door 41 is closed. Door 42 is closed. Door 43 is closed. Door 44 is closed. Door 45 is closed. Door 46 is closed. Door 47 is closed. Door 48 is closed. Door 49 is open. Door 50 is closed. Door 51 is closed. Door 52 is closed. Door 53 is closed. Door 54 is closed. Door 55 is closed. Door 56 is closed. Door 57 is closed. Door 58 is closed. Door 59 is closed. Door 60 is closed. Door 61 is closed. Door 62 is closed. Door 63 is closed. Door 64 is open. Door 65 is closed. Door 66 is closed. Door 67 is closed. Door 68 is closed. Door 69 is closed. Door 70 is closed. Door 71 is closed. Door 72 is closed. Door 73 is closed. Door 74 is closed. Door 75 is closed. Door 76 is closed. Door 77 is closed. Door 78 is closed. Door 79 is closed. Door 80 is closed. Door 81 is open. Door 82 is closed. Door 83 is closed. Door 84 is closed. Door 85 is closed. Door 86 is closed. Door 87 is closed. Door 88 is closed. Door 89 is closed. Door 90 is closed. Door 91 is closed. Door 92 is closed. Door 93 is closed. Door 94 is closed. Door 95 is closed. Door 96 is closed. Door 97 is closed. Door 98 is closed. Door 99 is closed. Door 100 is open.  ## FUZE BASIC READ x,y,zPRINT "Open doors: ";x;" ";CYCLE z=x+y PRINT z;" "; x=z y=y+2REPEAT UNTIL z>=100DATA 1,3,0END ## Fōrmulæ In this page you can see the solution of this task. Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text (more info). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for transportation effects more than visualization and edition. The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code. ## Gambas Public Sub Main()Dim bDoor As New BooleanDim siCount1, siCount2, siStart As Short For siCount1 = 1 To 100 Inc siStart For siCount2 = siStart To 100 Step siCount1 bDoor[siCount2] = Not bDoor[siCount2] NextNext For siCount1 = 1 To 100 If bDoor[siCount1] Then Print siCount1;;Next End Output: 1 4 9 16 25 36 49 64 81 100  ## GAP doors := function(n) local a,j,s; a := [ ]; for j in [1 .. n] do a[j] := 0; od; for s in [1 .. n] do j := s; while j <= n do a[j] := 1 - a[j]; j := j + s; od; od; return Filtered([1 .. n], j -> a[j] = 1);end; doors(100);# [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ] ## Genie  // 100 doors problem// Author: Sinuhe masan (2019)init // 100 elements array of boolean type doors:bool for var i = 1 to 100 doors[i] = false // set all doors closed for var i = 1 to 100 j:int = i while j <= 100 do doors[j] = not doors[j] j = j + i print("Doors open: ") for var i = 1 to 100 if doors[i] stdout.printf ("%d ", i)  ## Glee 100 *=0=>d  create vector 1..100, create bit pattern d, marking all equal to 0:for (1..100[.s]){  loop s from 1 to 100 d^(100 %s *=0 )=>d;}  d = d xor (bit pattern of vector 1..100 % s)d  output d  The resulting output is the bit pattern showing the state of the 100 doors: Result:10010000 10000001 00000000 10000000 00010000 00000000 10000000 00000001 00000000 00000000 10000000 00000000 0001 ## GML var doors,a,i;//Sets up the array for all of the doors.for (i = 1; i<=100; i += 1) { doors[i]=0; } //This first for loop goes through and passes the interval down to the next for loop.for (i = 1; i <= 100; i += 1;) { //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..) for (a = 0; a <= 100; a += i;) { //Opens or closes a door. doors[a] = !doors[a]; } }open_doors = ''; //This for loop goes through the array and checks for open doors.//If the door is open it adds it to the string then displays the string.for (i = 1; i <= 100; i += 1;) { if (doors[i] == 1) { open_doors += "Door Number "+string(i)+" is open#"; } }show_message(open_doors);game_end(); ## Go unoptimized package main import "fmt" func main() { doors := bool{} // the 100 passes called for in the task description for pass := 1; pass <= 100; pass++ { for door := pass-1; door < 100; door += pass { doors[door] = !doors[door] } } // one more pass to answer the question for i, v := range doors { if v { fmt.Print("1") } else { fmt.Print("0") } if i%10 == 9 { fmt.Print("\n") } else { fmt.Print(" ") } }} Output: 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1  optimized package main import "fmt" func main() { var door int = 1 var incrementer = 0 for current := 1; current <= 100; current++ { fmt.Printf("Door %d ", current) if current == door { fmt.Printf("Open\n") incrementer++ door += 2*incrementer + 1 } else { fmt.Printf("Closed\n") } }} optimized 2 // 100 (optimized) doors in Go package main import ( "fmt" "math") func main() { for i := 1; i <= 100; i++ { f := math.Sqrt(float64(i)) if math.Mod(f, 1) == 0 { fmt.Print("O") } else { fmt.Print("-") } } fmt.Println()} Output: O--O----O------O--------O----------O------------O--------------O----------------O------------------O  ## Golfscript 100:c;[{0}c*]:d;c,{.c,>$$%{.d<\.d=1^\)d>++:d;}/}/[c,{)"door "\+" is"+}%d{{"open"}{"closed"}if}%]zip{" "*puts}/

optimized with sqrt (Original version of GolfScript has no sqrt operator, but it can be added easily; the code was tested using a work-in-progress C interpreter for a language compatible enough with Golfscript)

100,{)}%{:d.sqrt 2?={"open"}{"close"}if"door "d+" is "+\+puts}/

optimized without sqrt

[{"close"}100*]:d;10,{)2?(.d<\["open"]\)d>++:d;}/[100,{)"door "\+" is"+}%d]zip{" "*puts}/

## Gosu

unoptimized

 uses java.util.Arrays var doors = new booleanArrays.fill( doors, false ) for( pass in 1..100 ) {    var counter = pass-1    while( counter < 100 ) {        doors[counter] = !doors[counter]        counter += pass  }} for( door in doors index i ) {    print( "door ${i+1} is${door ? 'open' : 'closed'}" )}

optimized

 var door = 1var delta = 0 for( i in 1..100 ) {    if( i == door ) {        print( "door ${i} is open" ) delta++ door += 2*delta + 1 } else { print( "door${i} is closed" )    }}

## Groovy

unoptimized

doors = [false] * 100(0..99).each {   it.step(100, it + 1) {      doors[it] ^= true   }}(0..99).each {   println("Door #${it + 1} is${doors[it] ? 'open' : 'closed'}.")}

optimized a Using square roots

(1..100).each {   println("Door #${it} is${Math.sqrt(it).with{it==(int)it} ? 'open' : 'closed'}.")}

optimized b Without using square roots

doors = ['closed'] * 100(1..10).each { doors[it**2 - 1] = 'open' }(0..99).each {   println("Door #${it + 1} is${doors[it]}.")}

## GW-BASIC

10 DIM A(100)20 FOR OFFSET = 1 TO 10030      FOR I = 0 TO 100 STEP OFFSET40              A(I) = A(I) + 150      NEXT I60 NEXT OFFSET70 ' Print "opened" doors80 FOR I = 1 TO 10090      IF A(I) MOD 2 = 1 THEN PRINT I100 NEXT I

Output:

1
4
9
16
25
36
49
64
81
100


## Harbour

Unoptimized code:

#define ARRAY_ELEMENTS 100PROCEDURE Main()   LOCAL aDoors := Array( ARRAY_ELEMENTS )   LOCAL i, j    AFill( aDoors, .F. )   FOR i := 1 TO ARRAY_ELEMENTS      FOR j := i TO ARRAY_ELEMENTS STEP i         aDoors[ j ] = ! aDoors[ j ]      NEXT   NEXT   AEval( aDoors, {|e, n| QQout( Padl(n,3) + " is " + Iif(aDoors[n], "*open*", "closed" ) + "|" ), Iif( n%5 == 0, Qout(), e:=NIL) } )   RETURN

Optimized code

#define ARRAY_ELEMENTS 100PROCEDURE Main()   LOCAL aDoors := Array( ARRAY_ELEMENTS )    AFill( aDoors, .F. )   AEval( aDoors, {|e, n| aDoors[n] := e := Iif( Int(Sqrt(n))==Sqrt(n), .T., .F. ) } )   AEval( aDoors, {|e, n| QQout( Padl(n,3) + " is " + Iif(aDoors[n], "*open*", "closed" ) + "|" ), Iif( n%5 == 0, Qout(), e:=NIL )} )   RETURN

Output:

 1 is *open*|  2 is closed|  3 is closed|  4 is *open*|  5 is closed|
6 is closed|  7 is closed|  8 is closed|  9 is *open*| 10 is closed|
11 is closed| 12 is closed| 13 is closed| 14 is closed| 15 is closed|
16 is *open*| 17 is closed| 18 is closed| 19 is closed| 20 is closed|
21 is closed| 22 is closed| 23 is closed| 24 is closed| 25 is *open*|
26 is closed| 27 is closed| 28 is closed| 29 is closed| 30 is closed|
31 is closed| 32 is closed| 33 is closed| 34 is closed| 35 is closed|
36 is *open*| 37 is closed| 38 is closed| 39 is closed| 40 is closed|
41 is closed| 42 is closed| 43 is closed| 44 is closed| 45 is closed|
46 is closed| 47 is closed| 48 is closed| 49 is *open*| 50 is closed|
51 is closed| 52 is closed| 53 is closed| 54 is closed| 55 is closed|
56 is closed| 57 is closed| 58 is closed| 59 is closed| 60 is closed|
61 is closed| 62 is closed| 63 is closed| 64 is *open*| 65 is closed|
66 is closed| 67 is closed| 68 is closed| 69 is closed| 70 is closed|
71 is closed| 72 is closed| 73 is closed| 74 is closed| 75 is closed|
76 is closed| 77 is closed| 78 is closed| 79 is closed| 80 is closed|
81 is *open*| 82 is closed| 83 is closed| 84 is closed| 85 is closed|
86 is closed| 87 is closed| 88 is closed| 89 is closed| 90 is closed|
91 is closed| 92 is closed| 93 is closed| 94 is closed| 95 is closed|
96 is closed| 97 is closed| 98 is closed| 99 is closed|100 is *open*|


unoptimized

data Door  = Open  | Closed  deriving (Eq, Show) toggle :: Door -> Doortoggle Open = Closedtoggle Closed = Open toggleEvery :: Int -> [Door] -> [Door]toggleEvery k = zipWith toggleK [1 ..]  where    toggleK n door      | n mod k == 0 = toggle door      | otherwise = door run :: Int -> [Door]run n = foldr toggleEvery (replicate n Closed) [1 .. n] main :: IO ()main = print $filter ((== Open) . snd)$ zip [1 ..] (run 100)
Output:
[(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]

optimized (without using square roots)

gate :: Eq a => [a] -> [a] -> [Door]gate (x:xs) (y:ys) | x == y  =  Open   : gate xs ysgate (x:xs) ys               =  Closed : gate xs ysgate []     _                =  [] run n = gate [1..n] [k*k | k <- [1..]]

alternatively, returning a list of all open gates, it's a one-liner:

run n = takeWhile (< n) [k*k | k <- [1..]]

## Haxe

class RosettaDemo{    static public function main()    {        findOpenLockers(100);    }     static function findOpenLockers(n : Int)    {        var i = 1;         while((i*i) <= n)        {            Sys.print(i*i + "\n");            i++;        }    }}

## HicEst

Unoptimized

REAL :: n=100, open=1, door(n) door = 1 - open ! = closedDO i = 1, n  DO j = i, n, i    door(j) = open - door(j)  ENDDOENDDODLG(Text=door, TItle=SUM(door)//" doors open")

Optimized

door = 1 - open ! = closedDO i = 1, n^0.5  door(i*i) = openENDDODLG(Text=door, TItle=SUM(door)//" doors open")

## HolyC

Translation of: C
U8 is_open;U8 pass = 0, door = 0; /* do the 100 passes */for (pass = 0; pass < 100; ++pass)  for (door = pass; door < 100; door += pass + 1)    is_open[door] = !is_open[door]; /* output the result */for (door = 0; door < 100; ++door)  if (is_open[door])    Print("Door #%d is open.\n", door + 1);  else    Print("Door #%d is closed.\n", door + 1);

## Hoon

|^=/  doors=(list ?)  (reap 100 %.n)=/  passes=(list (list ?))  (turn (gulf 1 100) pass-n)|-?~  passes  doors$(doors (toggle doors i.passes), passes t.passes)++ pass-n |= [email protected] (turn (gulf 1 100) |=([email protected] =((mod k n) 0)))++ toggle |= [a=(list ?) b=(list ?)] =| c=(list ?) |- ?: |(?=(~ a) ?=(~ b)) (flop c)$(a t.a, b t.b, c [=((mix i.a i.b) 1) c])--

## Inform 7

Works with: Z-machine version 8
Hallway is a room. A toggle door is a kind of thing.A toggle door can be open or closed. It is usually closed.A toggle door has a number called the door number.Understand the door number property as referring to a toggle door.Rule for printing the name of a toggle door: say "door #[door number]". There are 100 toggle doors. When play begins (this is the initialize doors rule):	let the next door number be 1;	repeat with D running through toggle doors:		now the door number of D is the next door number;		increment the next door number. To toggle (D - open toggle door): now D is closed.To toggle (D - closed toggle door): now D is open. When play begins (this is the solve puzzle rule):	let the door list be the list of toggle doors;	let the door count be the number of entries in the door list;	repeat with iteration running from 1 to 100:		let N be the iteration;		while N is less than the door count:			toggle entry N in the door list;			increase N by the iteration;	say "Doors left open: [list of open toggle doors].";	end the story.

## Informix 4GL

 MAIN    DEFINE        i, pass SMALLINT,        doors ARRAY OF SMALLINT     FOR i = 1 TO 100        LET doors[i] = FALSE    END FOR     FOR pass = 1 TO 100        FOR i = pass TO 100 STEP pass            LET doors[i] = NOT doors[i]        END FOR    END FOR     FOR i = 1 TO 100        IF doors[i]          THEN DISPLAY i USING "Door <<& is open"          ELSE DISPLAY i USING "Door <<& is closed"        END IF    END FOREND MAIN

## Io

simple boolean list solution:

doors := List clone100 repeat(doors append(false))for(i,1,100,    for(x,i,100, i, doors atPut(x - 1, doors at(x - 1) not)))doors foreach(i, x, if(x, "Door #{i + 1} is open" interpolate println))

Optimized solution:

(Range 1 to(10) asList) foreach(v, "Door #{v ** 2} is open." interpolate println)
Sample output:
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.

## Ioke

Unoptimized Object Oriented solution.

NDoors = Origin mimic NDoors Toggle = Origin mimic do(  initialize = method(toggled?, @toggled? = toggled?)  toggle! = method(@toggled? = !toggled?. self)) NDoors Doors = Origin mimic do(  initialize = method(n,    @n = n    @doors = {} addKeysAndValues(1..n, (1..n) map(_, NDoors Toggle mimic(false)))  )  numsToToggle = method(n, for(x <- ([email protected]), (x % n) zero?, x))  toggleThese = method(nums, nums each(x, @doors[x] = @doors at(x) toggle))  show = method(@doors filter:dict(value toggled?) keys sort println)) ; Test codex = NDoors Doors mimic(100)(1..100) each(n, x toggleThese(x numsToToggle(n)))x show

## J

unoptimized

   ~:/ (100 $- {. 1:)"0 >:i.1001 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ... ~:/ 0=|/~ >:i.100 NB. alternative1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ... optimized  (e. *:) 1+i.1001 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ... 1 (<:*:i.10)} 100$0  NB. alternative1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...

with formatting

   'these doors are open' ; >: I. (>:i.100) e. *: i.11+------------------------------------------------+¦these doors are open¦1 4 9 16 25 36 49 64 81 100¦+------------------------------------------------+

## Janet

 (def doors (seq [_ :range [0 100]] false)) (loop [pass :range [0 100]       door :range [pass 100 (inc pass)]]  (put doors door (not (doors door)))) (print "open doors: " ;(seq [i :range [0 100] :when (doors i)] (string (inc i) " ")))

Output:

open doors: 1 4 9 16 25 36 49 64 81 100


## Java

### With an array of boolean

class HundredDoors {    public static void main(String[] args) {        boolean[] doors = new boolean;         for (int i = 1; i < doors.length; i++) {            for (int j = i; j < doors.length; j += i) {                doors[j] = !doors[j];            }        }         for (int i = 1; i < doors.length; i++) {            if (doors[i]) {                System.out.printf("Door %d is open.%n", i);            }        }    }}

### With a BitSet

import java.util.BitSet; public class HundredDoors {    public static void main(String[] args) {        final int n = 100;        var a = new BitSet(n);        for (int i = 1; i <= n; i++) {            for (int j = i - 1; j < n; j += i) {                a.flip(j);            }        }        a.stream().map(i -> i + 1).forEachOrdered(System.out::println);    }}

### Only print the result

class HundredDoors {    public static void main(String[] args) {        for (int i = 1; i <= 10; i++)            System.out.printf("Door %d is open.%n", i * i);    }}

Output:

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.

If only printing the result is required, using streams.

import java.util.stream.Collectors;import java.util.stream.IntStream; class HundredDoors {    public static void main(String args[]) {        String openDoors = IntStream.rangeClosed(1, 100)                .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i)                .mapToObj(Integer::toString)                .collect(Collectors.joining(", "));        System.out.printf("Open doors: %s%n", openDoors);    }}

Output:

Open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100


## JavaScript

### ES5

#### Iterative

 var doors=[];for(var i=0;i<100;i++) doors[i]=false;             //create doorsfor(var i=1;i<=100;i++) for(var i2=i-1,g;i2<100;i2+=i)  doors[i2]=!doors[i2];      //toggle doorsfor(var i=1;i<=100;i++)      //read doors console.log("Door %d is %s",i,doors[i-1]?"open":"closed")

#### Functional Composition

Naive search

(function (n) {    'use strict';      // finalDoors :: Int -> [(Int, Bool)]    function finalDoors(n) {        var lstRange = range(1, n);         return lstRange            .reduce(function (a, _, k) {                var m = k + 1;                 return a.map(function (x, i) {                    var j = i + 1;                     return [j, j % m ? x : !x];                });            }, zip(                lstRange,                replicate(n, false)            ));    };       // GENERIC FUNCTIONS     // zip :: [a] -> [b] -> [(a,b)]    function zip(xs, ys) {        return xs.length === ys.length ? (            xs.map(function (x, i) {                return [x, ys[i]];            })        ) : undefined;    }     // replicate :: Int -> a -> [a]    function replicate(n, a) {        var v = [a],            o = [];         if (n < 1) return o;        while (n > 1) {            if (n & 1) o = o.concat(v);            n >>= 1;            v = v.concat(v);        }        return o.concat(v);    }     // range(intFrom, intTo, optional intStep)    // Int -> Int -> Maybe Int -> [Int]    function range(m, n, delta) {        var d = delta || 1,            blnUp = n > m,            lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,            a = Array(lng),            i = lng;         if (blnUp)            while (i--) a[i] = (d * i) + m;        else            while (i--) a[i] = m - (d * i);         return a;    }      return finalDoors(n)        .filter(function (tuple) {            return tuple;        })        .map(function (tuple) {            return {                door: tuple,                open: tuple            };        }); })(100);
Output:
[{"door":1, "open":true}, {"door":4, "open":true}, {"door":9, "open":true}, {"door":16, "open":true}, {"door":25, "open":true}, {"door":36, "open":true}, {"door":49, "open":true}, {"door":64, "open":true}, {"door":81, "open":true}, {"door":100, "open":true}]

#### Optimized ( iterative )

for (var door = 1; door <= 100; door++) {  var sqrt = Math.sqrt(door);  if (sqrt === (sqrt | 0)) {    console.log("Door %d is open", door);  }}

Simple for loop. Optimizing the optimized?

for(var door=1;i<10/*Math.sqrt(100)*/;i++){ console.log("Door %d is open",i*i);}

#### Optimized ( functional )

The question of which doors are flipped an odd number of times reduces to the question of which numbers have an odd number of integer factors.

We can simply search for these:

(function (n) {    'use strict';     return range(1, 100)        .filter(function (x) {            return integerFactors(x)                .length % 2;        });     function integerFactors(n) {        var rRoot = Math.sqrt(n),            intRoot = Math.floor(rRoot),             lows = range(1, intRoot)            .filter(function (x) {                return (n % x) === 0;            });         // for perfect squares, we can drop the head of the 'highs' list        return lows.concat(lows.map(function (x) {                return n / x;            })            .reverse()            .slice((rRoot === intRoot) | 0));    }     // range(intFrom, intTo, optional intStep)    // Int -> Int -> Maybe Int -> [Int]    function range(m, n, delta) {        var d = delta || 1,            blnUp = n > m,            lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,            a = Array(lng),            i = lng;         if (blnUp)            while (i--) a[i] = (d * i) + m;        else            while (i--) a[i] = m - (d * i);         return a;    } })(100);

Or we can note, on inspection and further reflection, that only perfect squares have odd numbers of integer factors - all other numbers have only matched pairs of factors - low factors below the non-integer square root, and the corresponding quotients above the square root. In the case of perfect squares, the additional integer square root (not paired with any other factor than itself) makes the total number of distinct factors odd.

(function (n) {    'use strict';     return perfectSquaresUpTo(100);     function perfectSquaresUpTo(n) {        return range(1, Math.floor(Math.sqrt(n)))            .map(function (x) {                return x * x;            });    }     // GENERIC     // range(intFrom, intTo, optional intStep)    // Int -> Int -> Maybe Int -> [Int]    function range(m, n, delta) {        var d = delta || 1,            blnUp = n > m,            lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,            a = Array(lng),            i = lng;         if (blnUp)            while (i--) a[i] = (d * i) + m;        else            while (i--) a[i] = m - (d * i);        return a;    } })(100);
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

### ES6

 Array.apply(null, { length: 100 })  .map((v, i) => i + 1)    .forEach(door => {       var sqrt = Math.sqrt(door);        if (sqrt === (sqrt | 0)) {        console.log("Door %d is open", door);      }     });

// Array comprehension style[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => {   var door = i + 1  var sqrt = Math.sqrt(door);    if (sqrt === (sqrt | 0)) {    console.log("Door %d is open", door);  } });

The result is always:

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

Or using a more general function for listing perfect squares:

(function (n) {      // ONLY PERFECT SQUARES HAVE AN ODD NUMBER OF INTEGER FACTORS    // (Leaving the door open at the end of the process)      return perfectSquaresUpTo(n);      // perfectSquaresUpTo :: Int -> [Int]    function perfectSquaresUpTo(n) {        return range(1, Math.floor(Math.sqrt(n)))            .map(x => x * x);    }      // GENERIC     // range(intFrom, intTo, optional intStep)    // Int -> Int -> Maybe Int -> [Int]    function range(m, n, step) {        let d = (step || 1) * (n >= m ? 1 : -1);         return Array.from({            length: Math.floor((n - m) / d) + 1        }, (_, i) => m + (i * d));    } })(100);
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

## jq

jq arrays have 0 as their index origin, but in the following, the 100 doors are numbered from 1 to 100.

Solution by simulation
# Solution for n doors:def doors(n):   def print:    . as $doors | range(1; length+1) | if$doors[.] then "Door \(.) is open" else empty end;     [range(n+1)|null] as $doors | reduce range(1; n+1) as$run      ( $doors; reduce range($run; n+1; $run ) as$door                  ( .; .[$door] = (.[$door] | not) ) )  | print ;
Analytical solution
# Solution for 100 doors:def solution:  range(1;11) | "Door \(. * .) is open";

## Julia

Simple:

• falses(100) creates a 100-element Bool array filled with false values,
• 'b in a:a:100' translates to 'start:step:end',
• string concatenation by '*'.

doors = falses(100)for a in 1:100, b in a:a:100    doors[b] = !doors[b]endfor a = 1:100    println("Door $a is " * (doors[a] ? "open." : "closed.")) end Gimmicky-optimized: for i in 1:10 println("Door$(i^2) is open.") end

## K

unoptimized / converted from Q .

 closed open ![ ; 2 ] @ #:' 1 _ = ,/ &:' 0 = t !\:/: t : ! 101

optimized / 1 origin indices

 ( 1 + ! 10 ) ^ 2

/ As parameterized function :

 { ( 1 + ! _ x ^ % 2 ) ^ 2 } 100

## Klong

### unoptimized

 flip::{,/{(1-*x),1_x}'x:#y}i::0;(100{i::i+1;flip(i;x)}:*100:^0)?1

### optimized

 (1+!9)^2

## Kotlin

fun oneHundredDoors(): List<Int> {    val doors = BooleanArray(100, { false })    for (i in 0..99) {        for (j in i..99 step (i + 1)) {            doors[j] = !doors[j]        }    }    return doors        .mapIndexed { i, b -> i to b }        .filter { it.second }        .map { it.first + 1 }}

## KQL

range InitialDoor from 1 to 100 step 1| extend DoorsVisited=range(InitialDoor, 100, InitialDoor)| mvexpand DoorVisited=DoorsVisited to typeof(int)| summarize VisitCount=count() by DoorVisited| project Door=DoorVisited, IsOpen=(VisitCount % 2) == 1

## LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code. Optimized

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code. ## langur

### not optimized

Works with: langur version 0.8.11
var .doors = arr 100, false for .i of .doors {    for .j = .i; .j <= len(.doors); .j += .i {        .doors[.j] = not .doors[.j]    }} writeln wherekeys .doors

We could also use a for loop value to produce the output (instead of the wherekeys function), as in the following example.

Works with: langur version 0.8.1
writeln for[=[]] .i of .doors { if(.doors[.i]: _for ~= [.i]) }

Or, we could use the foldfrom() function to produce the output.

writeln foldfrom(f if(.b: .a~[.c]; .a), [], .doors, series 1..len .doors)

### optimized

writeln map(f .x ^ 2, series 1..10)
Works with: langur version 0.8.11
writeln map f{^2}, 1..10
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

## lambdatalk

Translation from Python

 1) unoptimized version {def doors {A.new  {S.map {lambda {} false} {S.serie 1 100}}}}-> doors {def toggle {lambda {:i :a}  {let { {_ {A.set! :i {not {A.get :i :a}} :a} }}}}}-> toggle {S.map {lambda {:b}  {S.map {lambda {:i} {toggle :i {doors}}}   {S.serie :b 99 {+ :b 1}}}}   {S.serie 0 99}} -> {S.replace \s by space in  {S.map {lambda {:i} {if {A.get :i {doors}} then {+ :i 1} else}}   {S.serie 0 99}}} -> 1 4 9 16 25 36 49 64 81 100 2.2) optimized version {S.replace \s by space in  {S.map {lambda {:i}         {let { {:root {sqrt :i}} }               {if {= :root {round :root}}                then {* :root :root}               else}}}        {S.serie 1 100}}} -> 1 4 9 16 25 36 49 64 81 100

## Lasso

### Loop

loop(100) => {^	local(root = math_sqrt(loop_count))	local(state = (#root == math_ceil(#root) ? '<strong>open</strong>' | 'closed'))	#state != 'closed' ? 'Door ' + loop_count + ': ' + #state + '<br>'^}
Output:
Door 1: open
Door 4: open
Door 9: open
Door 16: open
Door 25: open
Door 36: open
Door 49: open
Door 64: open
Door 81: open
Door 100: open

## Latitude

use 'format importAllSigils. doors := Object clone.doors missing := { False. }.doors check := {  self slot ($1 ordinal).}.doors toggle := { self slot ($1 ordinal) = self slot ($1 ordinal) not.}.1 upto 101 do { takes '[i]. local 'j = i. while { j <= 100. } do { doors toggle (j). j = j + i. }.}.$stdout printf: ~fmt "The open doors are: ~A", 1 upto 101 filter { doors check. } to (Array).

## Lhogho

This implementation defines 100 variables, named "1 through "100, rather than using a list. Thanks to Pavel Boytchev, the author of Lhogho, for help with the code.

to doors	;Problem 100 Doors 	;Lhogho 	for "p [1 100] 	[		make :p "false	] 	for "a [1 100 1]	[		for "b [:a 100 :a]		[			if :b < 101 			[				make :b not thing :b			]		]	] 	for "c [1 100]	[		if thing :c 		[ 			(print "door :c "is "open) 		]	] end doors

## Liberty BASIC

dim doors(100)for pass = 1 to 100    for door = pass to 100 step pass        doors(door) = not(doors(door))    next doornext passprint "open doors ";for door = 1 to 100    if doors(door) then print door;"  ";next door

## Mirah

import java.util.ArrayList class Door	:state 	def initialize		@state=false	end 	def closed?; [email protected]; end	def open?; @state; end 	def close; @state=false; end	def open; @state=true; end 	def toggle		if closed?			open		else			close		end	end 	def toString; Boolean.toString(@state); endend doors=ArrayList.new1.upto(100) do    doors.add(Door.new)end  1.upto(100) do |multiplier|    index = 0    doors.each do |door|        Door(door).toggle if (index+1)%multiplier == 0        index += 1    endend i = 0doors.each do |door|     puts "Door #{i+1} is #{door}."    i+=1end

## Myrddin

 use std const main = {	var isopen	: bool 	std.slfill(isopen[:], false)	for var i = 0; i < isopen.len; i++		for var j = i; j < isopen.len; j += i + 1			isopen[j] = !isopen[j]		;;	;; 	for var i = 0; i < isopen.len; i++		if isopen[i]			std.put("door {} is open\n", i + 1)		;;	;;}
Output:
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


## MySQL

 DROP PROCEDURE IF EXISTS one_hundred_doors; DELIMITER | CREATE PROCEDURE one_hundred_doors (n INT)BEGIN  DROP TEMPORARY TABLE IF EXISTS doors;   CREATE TEMPORARY TABLE doors (    id INTEGER NOT NULL,    open BOOLEAN DEFAULT FALSE,    PRIMARY KEY (id)  );   SET @i = 1;  create_doors: LOOP    INSERT INTO doors (id, open) values (@i, FALSE);    SET @i = @i + 1;    IF @i > n THEN      LEAVE create_doors;    END IF;  END LOOP create_doors;   SET @i = 1;  toggle_doors: LOOP    UPDATE doors SET open = NOT open WHERE MOD(id, @i) = 0;    SET @i = @i + 1;    IF @i > n THEN      LEAVE toggle_doors;    END IF;  END LOOP toggle_doors;   SELECT id FROM doors WHERE open;END| DELIMITER ; CALL one_hundred_doors(100);
Output:
+-----+
| id  |
+-----+
|   1 |
|   4 |
|   9 |
|  16 |
|  25 |
|  36 |
|  49 |
|  64 |
|  81 |
| 100 |
+-----+
10 rows in set (0.02 sec)


## Nanoquery

// allocate a boolean array with all closed doors (false)// we need 101 since there will technically be a door 0doors = {false} * 101 // loop through all the step lengths (1-100)for step in range(1, 100)	// loop through all the doors, stepping by step	for door in range(0, len(doors) - 1, step)		// change the state of the current door		doors[door] = !doors[door]	end forend for // loop through and print the doors that are open, skipping door 0for i in range(1, len(doors) - 1)	// if the door is open, display it	if doors[i]		println "Door " + i + " is open."	end ifend for

## NetRexx

unoptimized

/* NetRexx */options replace format comments java crossref symbols binary True  = Rexx(1 == 1)False = Rexx(\True) doors = False loop i_ = 1 to 100  loop j_ = 1 to 100    if 0 = (j_ // i_) then doors[j_] = \doors[j_]    end j_  end i_ loop d_ = 1 to 100  if doors[d_] then  state = 'open'  else  state = 'closed'   say 'Door Nr.' Rexx(d_).right(4) 'is' state  end d_

optimized (Based on the Java 'optimized' version)

Translation of: Java
/* NetRexx */options replace format comments java crossref symbols binary True  = (1 == 1)False = \True doors = boolean loop i_ = 0 to 9  doors[(i_ + 1) * (i_ + 1) - 1] = True;  end i_ loop i_ = 0 to 99  if doors[i_] then  state = 'open'  else  state = 'closed'   say 'Door Nr.' Rexx(i_ + 1).right(4) 'is' state  end i_

optimized 2 (Based on the Java 'optimized 2' version)

Translation of: Java
/* NetRexx */options replace format comments java crossref savelog symbols binary resultstring = '' loop i_ = 1 to 10  resultstring = resultstring || 'Door Nr.' Rexx(i_ * i_).right(4) 'is open\n'  end i_ say resultstring

optimized 3

/* NetRexx */ loop i = 1 to 10   say 'Door Nr.' i * i 'is open.'  end i

## NewLISP

(define (status door-num)    (let ((x (int (sqrt door-num))))     (if       (= (* x x) door-num) (string "Door " door-num " Open")       (string "Door " door-num " Closed")))) (dolist (n (map status (sequence 1 100)))  (println n))

Not optimized:

 (set 'Doors (array 100))  ;; Default value: nil (Closed) (for (x 0 99)    (for (y x 99 (+ 1 x))        (setf (Doors y) (not (Doors y))))) (for (x 0 99)  ;; Display open doors    (if (Doors x)        (println (+ x 1) " : Open")))

Output:

1 : Open
4 : Open
9 : Open
16 : Open
25 : Open
36 : Open
49 : Open
64 : Open
81 : Open
100 : Open


## Nial

unoptimized solution (works with Q'Nial7):

Output of the boolean array showing the status of the doors. Truth values in Nial arrays are shown as l(true) and o(false):

     n:=100;reduce xor (count n eachright mod count n eachall<1)looloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo looooooooooooooooool

Indices of the open doors:

     true findall (n:=100;reduce xor (count n eachright mod count n eachall<1))+11 4 9 16 25 36 49 64 81 100

optimized solution:

     count 10 power 21 4 9 16 25 36 49 64 81 100

## Nim

unoptimized:

from strutils import % const numDoors = 100var doors: array[1..numDoors, bool] for pass in 1..numDoors:  for door in countup(pass, numDoors, pass):    doors[door] = not doors[door] for door in 1..numDoors:  echo "Door $1 is$2." % [$door, if doors[door]: "open" else: "closed"] Challenging C++'s compile time computation: https://rosettacode.org/wiki/100_doors#C.2B.2B outputString is evaluated at compile time. Check the resulting binary in case of doubt. from strutils import % const numDoors = 100var doors {.compileTime.}: array[1..numDoors, bool] proc calcDoors(): string = for pass in 1..numDoors: for door in countup(pass, numDoors, pass): doors[door] = not doors[door] for door in 1..numDoors: result.add("Door$1 is $2.\n" % [$door, if doors[door]: "open" else: "closed"]) const outputString: string = calcDoors() echo outputString

## Oberon

MODULE Doors;  IMPORT Out;   PROCEDURE Do*;  (* In Oberon an asterisk after an identifier is an export mark *)    CONST N = 100; len = N + 1;    VAR i, j: INTEGER;      closed: ARRAY len OF BOOLEAN;  (* Arrays in Oberon always start with index 0; closed is not used *)  BEGIN    FOR i := 1 TO N DO closed[i] := TRUE END;    FOR i := 1 TO N DO      j := 1;      WHILE j < len DO        IF j MOD i = 0 THEN closed[j] := ~closed[j] END; INC(j)  (* ~ = NOT *)      END    END;    (* Print a state diagram of all doors *)    FOR i := 1 TO N DO       IF (i - 1) MOD 10 = 0 THEN Out.Ln END;      IF closed[i] THEN Out.String("- ") ELSE Out.String("+ ") END    END;  Out.Ln;    (* Print the numbers of the open doors *)    FOR i := 1 TO N DO       IF ~closed[i] THEN Out.Int(i, 0); Out.Char(" ") END    END;  Out.Ln  END Do; END Doors.

Execute: Doors.Do

Output:
+ – – + – – – – + –
– – – – – + – – – –
– – – – + – – – – –
– – – – – + – – – –
– – – – – – – – + –
– – – – – – – – – –
– – – + – – – – – –
– – – – – – – – – –
+ – – – – – – – – –
– – – – – – – – – +
1 4 9 16 25 36 49 64 81 100


## Objeck

optimized

 bundle Default {  class Doors {    function : Main(args : String[]) ~ Nil {      doors := Bool->New;       for(pass := 0; pass < 10; pass += 1;) {        doors[(pass + 1) * (pass + 1) - 1] := true;      };       for(i := 0; i < 100; i += 1;) {            IO.Console->GetInstance()->Print("Door #")->Print(i + 1)->Print(" is ");        if(doors[i]) {          "open."->PrintLine();        }        else {          "closed."->PrintLine();        };      };    }  }}

## Objective-C

A basic implementation in Objective-C:

This is a very basic Objective-C sample that shows the usage of standard types and classes such as NSInteger and NSMutableArray.

It uses modern Objective-C syntax such as literals, blocks, and a compiler module import statement.

 @import Foundation; int main(int argc, const char * argv[]) {    @autoreleasepool {         // Create a mutable array        NSMutableArray *doorArray = [@[] mutableCopy];         // Fill the doorArray with 100 closed doors        for (NSInteger i = 0; i < 100; ++i) {            doorArray[i] = @NO;        }         // Do the 100 passes        for (NSInteger pass = 0; pass < 100; ++pass) {            for (NSInteger door = pass; door < 100; door += pass+1) {                doorArray[door] = [doorArray[door]  isEqual: @YES] ? @NO : @YES;            }        }         // Print the results        [doorArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {            if ([obj isEqual: @YES]) {                NSLog(@"Door number %lu is open", idx + 1);            }        }];    }}

A more typical implementation in Objective-C:

This example is more along the lines of what typical Objective-C program would look like.

Language features used include:

• MVC design pattern with separate classes for the data model, user interface, and controller (Here, main steps in to represent the controller class.)
• Class category to extend the standard NSMutableArray class to add doors without a subclass
• Class inheritance in the DoorViewClass when subclassing NSObject
• Pragma mark statements for IDE navigation in Xcode

In a real world program classes are normally separated into different files.

 @import Foundation; #pragma mark - Classes////////////////////////////////////////////////////// Model class header - A we are using a category to add a method to MSMutableArray@interface NSMutableArray (DoorModelExtension) - (void)setNumberOfDoors:(NSUInteger)doors; @end // Model class implementation@implementation NSMutableArray (DoorModelExtension) - (void)setNumberOfDoors:(NSUInteger)doors {    // Fill the doorArray with 100 closed doors    for (NSInteger i = 0; i < doors; ++i) {        self[i] = @NO;    }}@end//////////////////////////////////////////////////// // View class header - A simple class to handle printing our values@interface DoorViewClass : NSObject - (void)printResultsOfDoorTask:(NSMutableArray *)doors; @end // View class implementation@implementation DoorViewClass - (void)printResultsOfDoorTask:(NSMutableArray *)doors {     // Print the results, using an enumeration block for easy index tracking    [doors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {        if ([obj isEqual: @YES]) {            NSLog(@"Door number %lu is open", idx + 1);        }    }];} @end//////////////////////////////////////////////////// #pragma mark - main// With our classes set we can use them from our controller, in this case mainint main(int argc, const char * argv[]) {     // Init our classes    NSMutableArray *doorArray = [NSMutableArray array];    DoorViewClass *doorView = [DoorViewClass new];     // Use our class category to add the doors    [doorArray setNumberOfDoors:100];     // Do the 100 passes    for (NSUInteger pass = 0; pass < 100; ++pass) {        for (NSUInteger door = pass; door < 100; door += pass+1) {            doorArray[door] = [doorArray[door]  isEqual: @YES] ? @NO : @YES;        }    }     // Print the results    [doorView printResultsOfDoorTask:doorArray]; }

## OCaml

unoptimized

let max_doors = 100 let show_doors =  Array.iteri (fun i x -> Printf.printf "Door %d is %s\n" (i+1)                                        (if x then "open" else "closed")) let flip_doors doors =  for i = 1 to max_doors do    let rec flip idx =      if idx < max_doors then begin        doors.(idx) <- not doors.(idx);        flip (idx + i)      end    in flip (i - 1)  done;  doors let () =  show_doors (flip_doors (Array.make max_doors false))

optimized

let optimised_flip_doors doors =  for i = 1 to int_of_float (sqrt (float_of_int max_doors)) do    doors.(i*i - 1) <- true  done;  doors let () =  show_doors (optimised_flip_doors (Array.make max_doors false))

This variant is more functional style (loops are recursions), unoptimized, and we do rather 100 passes on first element, then 100 * second, to avoid mutable data structures and many intermediate lists.

type door = Open | Closed    (* human readable code *) let flipdoor = function Open -> Closed | Closed -> Open let string_of_door =         function Open -> "is open." | Closed -> "is closed." let printdoors ls =  let f i d = Printf.printf "Door %i %s\n" (i + 1) (string_of_door d)  in List.iteri f ls let outerlim = 100let innerlim = 100 let rec outer cnt accu =  let rec inner i door = match i > innerlim with (* define inner loop *)    | true  -> door                             | false -> inner (i + 1) (if (cnt mod i) = 0 then flipdoor door else door)  in (* define and do outer loop *)  match cnt > outerlim with  | true  -> List.rev accu  | false -> outer  (cnt + 1)  (inner 1 Closed :: accu) (* generate new entries with inner *) let () = printdoors (outer 1 [])

## Octave

doors = false(100,1);for i = 1:100  for j = i:i:100    doors(j) = !doors(j);  endforendforfor i = 1:100  if ( doors(i) )    s = "open";  else    s = "closed";  endif  printf("%d %s\n", i, s);endfor

See also the solutions in Matlab. They will work in Octave, too.

## Oforth

: doors| i j l |   100 false Array newWith dup ->l   100 loop: i [       i 100 i step: j [ l put ( j , j l at not ) ]       ] ;

## Ol

 (define (flip doors every)   (map (lambda (door num)            (mod (+ door (if (eq? (mod num every) 0) 1 0)) 2))      doors      (iota (length doors) 1))) (define doors   (let loop ((doors (repeat 0 100)) (n 1))      (if (eq? n 100)         doors         (loop (flip doors n) (+ n 1))))) (print "100th doors: " doors)

Output:

100th doors: (1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)


## OpenEdge/Progress

DEFINE VARIABLE lopen   AS LOGICAL     NO-UNDO EXTENT 100.DEFINE VARIABLE idoor   AS INTEGER     NO-UNDO.DEFINE VARIABLE ipass   AS INTEGER     NO-UNDO.DEFINE VARIABLE cresult AS CHARACTER   NO-UNDO. DO ipass = 1 TO 100:   idoor = 0.   DO WHILE idoor <= 100:      idoor = idoor + ipass.      IF idoor <= 100 THEN         lopen[ idoor ] = NOT lopen[ idoor ].   END.END. DO idoor = 1 TO 100:   cresult = cresult + STRING( lopen[ idoor ], "1  /0  " ).   IF idoor MODULO 10 = 0 THEN      cresult = cresult + "~r":U.END. MESSAGE cresult VIEW-AS ALERT-BOX.

## OxygenBasic

def    doors 100
int    door[doors],i ,j, c
string cr,tab,pr
'
for i=1 to doors
for j=i to doors step i
door[j]=1-door[j]
if door[j] then c++ else c--
next
next
'
cr=chr(13) chr(10)
pr="Doors Open: " c cr cr
'
for i=1 to doors
if door[i] then pr+=i cr
next
print pr


## Oz

declare  NumDoors = 100  NumPasses = 100   fun {NewDoor} closed end   fun {Toggle Door}     case Door of closed then open     [] open then closed     end  end   fun {Pass Doors I}     {List.mapInd Doors      fun {$Index Door} if Index mod I == 0 then {Toggle Door} else Door end end} end Doors0 = {MakeList NumDoors} {ForAll Doors0 NewDoor} DoorsN = {FoldL {List.number 1 NumPasses 1} Pass Doors0}in %% print open doors {List.forAllInd DoorsN proc {$ Index Door}      if Door == open then	 {System.showInfo "Door "#Index#" is open."}      end   end  }

Output:

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.


## PARI/GP

Unoptimized version.

 v=vector(d=100);/*set 100 closed doors*/for(i=1,d,forstep(j=i,d,i,v[j]=1-v[j]));for(i=1,d,if(v[i],print("Door ",i," is open.")))

Optimized version.

for(n=1,sqrt(100),print("Door ",n^2," is open."))

Unoptimized version.

 doors =vector(100);print("open doors are : ");for(i=1,100,for(j=i,100,doors[j]=!doors[j];j +=i-1))for(k=1,100,if(doors[k]==1,print1(" ",k)))

Output:

Open doors are:
1 4 9 16 25 36 49 64 81 100

## Pascal

Program OneHundredDoors; var   doors : Array[1..100] of Boolean;   i, j	 : Integer; begin   for i := 1 to 100 do      doors[i] := False;   for i := 1 to 100 do begin      j := i;      while j <= 100 do begin	 doors[j] := not doors[j];	 j := j + i      end   end;   for i := 1 to 100 do begin      Write(i, ' ');      if doors[i] then	 WriteLn('open')      else	 WriteLn('closed');   endend.

Optimized version.

program OneHundredDoors; {$APPTYPE CONSOLE} uses math, sysutils; var AOpendoors : String; ACloseDoors : String; i : Integer; begin for i := 1 to 100 do begin if (sqrt(i) = floor(sqrt(i))) then AOpenDoors := AOpenDoors + IntToStr(i) + ';' else ACloseDoors := ACloseDoors + IntToStr(i) +';'; end; WriteLn('Open doors: ' + AOpenDoors); WriteLn('Close doors: ' + ACloseDoors);end.  ## Perl unoptimized Works with: Perl version 5.x my @doors;for my$pass (1 .. 100) {    for (1 .. 100) {        if (0 == $_ %$pass) {            $doors[$_] = not $doors[$_];        };    };}; print "Door $_ is ",$doors[$_] ? "open" : "closed", "\n" for 1 .. 100; semi-optimized Works with: Perl version 5.x This version flips doors, but doesn't visit (iterate over) doors that aren't toggled. Note: I represent open doors as 0 and closed as 1 just for preference. (When I print it as a bit vector, 0 looks more like an open door to me.)  #!/usr/bin/perluse strict;use warnings; my @doors = (1) x 100;for my$N (1 .. 100) {   $doors[$_]=1-$doors[$_] for map { $_*$N - 1 } 1 .. int(100/$N);}print join("\n", map { "Door$_ is Open" } grep { ! $doors[$_-1] } 1 .. 100), "\n";print "The rest are closed\n";

optimized

Works with: Perl version 5.x
print "Door $_ is open\n" for map$_**2, 1 .. 10;
print "Door $_ is ", qw"closed open"[int sqrt == sqrt], "\n" for 1..100; while( ++$i <= 100 ){    $root = sqrt($i);    if ( int( $root ) ==$root )    {        print "Door $i is open\n"; } else { print "Door$i is closed\n";    }}

## Perl5i

 use perl5i::2; package doors {   use perl5i::2;  use Const::Fast;   const my $OPEN => 1; const my$CLOSED => 0;   # ----------------------------------------  # Constructor: door->new( @args );  # input: N - how many doors?  # returns: door object  #  method new($class: @args ) { my$self = bless {}, $class;$self->_init( @args );    return $self; } # ---------------------------------------- # class initializer. # input: how many doors? # sets N, creates N+1 doors ( door zero is not used ). # method _init($N ) {    $self->{N} =$N;    $self->{doors} = [ ($CLOSED) x ($N+1) ]; } # ---------------------------------------- #$self->toggle( $door_number ); # input: number of door to toggle. # OPEN a CLOSED door; CLOSE an OPEN door. # method toggle($which ) {    $self->{doors}[$which] = ( $self->{doors}[$which] == $OPEN ?$CLOSED                               : $OPEN ); } # ---------------------------------------- #$self->toggle_n( $cycle ); # input: number. # Toggle doors 0,$cycle, 2 * $cycle, 3 *$cycle, .. $self->{N} # method toggle_n($n ) {    $self->toggle($_)      for map { $n *$_ }          ( 1 .. int( $self->{N} /$n) );   }   # ----------------------------------------  # $self->toggle_all(); # Toggle every door, then every other door, every third door, ... # method toggle_all() {$self->toggle_n( $_ ) for ( 1 ..$self->{N} );  }    # ----------------------------------------  # $self->print_open(); # Print list of which doors are open. # method print_open() { say join ', ', grep {$self->{doors}[$_] ==$OPEN } ( 1 ... $self->{N} ); }} # ----------------------------------------------------------------------# Main Thread#my$doors = doors->new(100);$doors->toggle_all();$doors->print_open();

## Phix

### unoptimised

sequence doors = repeat(false,100) for i=1 to 100 do    for j=i to 100 by i do        doors[j] = not doors[j]    end forend for for i=1 to 100 do    if doors[i] == true then        printf(1,"Door #%d is open.\n", i)    end ifend for
Output:
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.


### optimised

function doors(integer n)-- returns the perfect squares<=ninteger door = 1, step = 1sequence res = {}    while door<=n do        res &= door        step += 2        door += step    end while    return resend function ?doors(100)
Output:
{1,4,9,16,25,36,49,64,81,100}


## Phixmonti

101 var l                           0 l repeat                       l for    var s    s l s 3 tolist    for        var i        i get not i set    endforendfor l for    var i    i get    if        i print " " print    endifendfor

Another way

100 var n   /# Number of doors #/0 n repeat  /# Make the doors #/ n for    dup    sqrt int    dup * over == if 1 swap set else drop endifendfor n for    "The door " print dup print " is " print    get if "OPEN." else "closed." endif print nlendfor "Time elapsed: " print msec print " seconds" print nl

## PHL

### unoptimized

module doors; extern printf; @Integer main [	@Array<@Boolean> doors = new @Array<@Boolean>.init(100);	var i = 1;	while (i <= 100) {		var j = i-1;		while (j < 100) {			doors.set(j, doors.get(j)::not);			j = j + i;		}		i = i::inc;	}	i = 0;	while (i < 100) {		printf("%i %s\n", i+1, iif(doors.get(i), "open", "closed"));		i = i::inc;	}	return 0;]

### optimized

Translation of: C#
module var; extern printf; @Integer main [	var door = 1;	var incrementer = 0;	var current = 1;        while (current <= 100)        {		printf("Door %i ", current);		if (current == door)		{			printf("open\n");			incrementer = incrementer::inc;			door = door + 2 * incrementer + 1;		}		else			printf("closed\n"); 		current = current + 1;         } 	return 0;]

## PHP

See: Demo optimized

<?phpfor ($i = 1;$i <= 100; $i++) {$root = sqrt($i);$state = ($root == ceil($root)) ? 'open' : 'closed';	echo "Door {$i}: {$state}\n";}?>

unoptimized

<?php$doors = array_fill(1, 100, false);for ($pass = 1; $pass <= 100; ++$pass) {	for ($nr = 1;$nr <= 100; ++$nr) { if ($nr % $pass == 0) {$doors[$nr] = !$doors[$nr]; } }}for ($nr = 1; $nr <= 100; ++$nr)	printf("Door %d: %s\n", $nr, ($doors[nr])?'open':'closed');?> ## Picat Non-optimized: doors(N) => Doors = new_array(N), foreach(I in 1..N) Doors[I] := 0 end, foreach(I in 1..N) foreach(J in I..I..N) Doors[J] := 1^Doors[J] end, if N <= 10 then print_open(Doors) end end, println(Doors), print_open(Doors), nl. print_open(Doors) => println([I : I in 1..Doors.length, Doors[I] == 1]).  optimized version 1: doors_opt(N) => foreach(I in 1..N) Root = sqrt(I), println([I, cond(Root == 1.0*round(Root), open, closed)]) end, nl.  optimized version 2: doors_opt2(N) => println([I**2 : I in 1..N, I**2 <= N]).  ## PicoLisp unoptimized (let Doors (need 100) (for I 100 (for (D (nth Doors I) D (cdr (nth D I))) (set D (not (car D))) ) ) (println Doors) ) optimized (let Doors (need 100) (for I (sqrt 100) (set (nth Doors (* I I)) T) ) (println Doors) ) Output in both cases: (T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL N IL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T) With formatting: (let Doors (need 100) (for I (sqrt 100) (set (nth Doors (* I I)) T) ) (make (for (N . D) Doors (when D (link N)) ) ) ) Output: (1 4 9 16 25 36 49 64 81 100) ## Piet ## Pike array onehundreddoors(){ array doors = allocate(100); foreach(doors; int i;) for(int j=i; j<100; j+=i+1) doors[j] = !doors[j]; return doors;} optimized version: array doors = map(enumerate(100,1,1), lambda(int x) { return sqrt((float)x)%1 == 0.0; }); write("%{%d %d %d %d %d %d %d %d %d %d\n%}\n", doors/10) output: 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1  ## PL/I  declare door(100) bit (1) aligned;declare closed bit (1) static initial ('0'b), open bit (1) static initial ('1'b);declare (i, inc) fixed binary; door = closed;inc = 1;do until (inc >= 100); do i = inc to 100 by inc; door(i) = ^door(i); /* close door if open; open it if closed. */ end; inc = inc+1;end; do i = 1 to 100; put skip edit ('Door ', trim(i), ' is ') (a); if door(i) then put edit (' open.') (a); else put edit (' closed.') (a);end;  ## PL/M Translation of: ALGOL W Tested using a PLM286 to C converter and a simple I/O library. DOORS: DO; /* find the first few squares via the unoptimised door flipping method */ /* External I/O routines */ WRITEBYTE:   PROCEDURE( B ) EXTERNAL; DECLARE B BYTE;   END WRITE$BYTE; WRITE$NL:     PROCEDURE      EXTERNAL;                   END WRITE$NL; /* End external routines */ DECLARE DOOR$MAX LITERALLY '100';    DECLARE DOOR$DCL LITERALLY '101'; DECLARE FALSE LITERALLY '0'; DECLARE TRUE LITERALLY '255'; MAIN: PROCEDURE; /* array of doors - door( i ) is true if open, false if closed */ DECLARE DOOR( DOOR$DCL ) BYTE;        DECLARE ( I, J )         BYTE;        /* set all doors to closed                                          */        DO I = 0 TO DOOR$MAX; DOOR( I ) = FALSE; END; /* repeatedly flip the doors */ DO I = 1 TO DOOR$MAX;            DO J = I TO DOOR$MAX BY I; DOOR( J ) = NOT DOOR( J ); END; END; /* display the results */ DO I = 1 TO DOOR$MAX;           IF DOOR( I ) THEN CALL WRITE$BYTE( I ); END; CALL WRITE$NL();    END MAIN;END DOORS;
Output:
   1   4   9  16  25  36  49  64  81 100


## PL/SQL

Unoptimized

 DECLARE  TYPE doorsarray IS VARRAY(100) OF BOOLEAN;  doors doorsarray := doorsarray();BEGIN doors.EXTEND(100);  --ACCOMMODATE 100 DOORS FOR i IN 1 .. doors.COUNT  --MAKE ALL 100 DOORS FALSE TO INITIALISE  LOOP     doors(i) := FALSE;                      END LOOP; FOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE LOOP      FOR k IN 1 .. 100        LOOP                  IF MOD(k,j)=0 THEN                      doors(k) := NOT doors(k);                   END IF;        END LOOP; END LOOP; FOR l IN 1 .. doors.COUNT  --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION  LOOP       DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE'                                                                 THEN 'OPEN'                                                               ELSE 'CLOSED'                                                         END);  END LOOP; END;

## Pointless

output =  range(1, 100)  |> map(visit(100))  |> println ---------------------------------------------------------- toggle(state) =  if state == Closed then Open else Closed ------------------------------------------------------------ Door state on iteration i is recursively-- defined in terms of previous door state visit(i, index) = cond {  case (i == 0) Closed  case (index % i == 0) toggle(lastState)  else lastState} where lastState = visit(i - 1, index)
Output:
[Open, Closed, Closed, Open, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open]

## Pony

Combined Optimized and Unoptimized

Probably also rather pointless in its use of actors, but, after all, they're cheap.

 actor Toggler    let doors:Array[Bool]    let env: Env    new create(count:USize,_env:Env) =>        var i:USize=0        doors=Array[Bool](count)        env=_env        while doors.size() < count do            doors.push(false)        end    be togglin(interval : USize)=>        var i:USize=0        try            while i < doors.size() do                doors.update(i,not doors(i)?)?                i=i+interval            end        else            env.out.print("Errored while togglin'!")        end    be printn(onlyOpen:Bool)=>        try            for i in doors.keys() do                if onlyOpen and not doors(i)? then                    continue                end                env.out.print("Door " + i.string() + " is " +                    if doors(i)? then                        "Open"                    else                        "closed"                    end)            end        else            env.out.print("Error!")        end        true actor OptimizedToggler    let doors:Array[Bool]    let env:Env    new create(count:USize,_env:Env)=>        env=_env        doors=Array[Bool](count)        while doors.size()<count do            doors.push(false)        end    be togglin()=>        var i:USize=0        if alreadydone then            return        end        try            doors.update(0,true)?            doors.update(1,true)?            while i < doors.size() do                i=i+1                let z=i*i                let x=z*z                if z > doors.size() then                    break                else                    doors.update(z,true)?                end                if x < doors.size() then                    doors.update(x,true)?                end            end        end    be printn(onlyOpen:Bool)=>        try            for i in doors.keys() do                if onlyOpen and not doors(i)? then                    continue                end                env.out.print("Door " + i.string() + " is " +                    if doors(i)? then                        "Open"                    else                        "closed"                    end)            end        else            env.out.print("Error!")        end        trueactor Main    new create(env:Env)=>        var count: USize =100        try            let index=env.args.find("-n",0,0,{(l,r)=>l==r})?            try            match env.args(index+1)?.read_int[USize]()?                | (let x:USize, _)=>count=x                end            else                env.out.print("You either neglected to provide an argument after -n or that argument was not an integer greater than zero.")                return            end        end        if env.args.contains("optimized",{(l,r)=>r==l}) then            let toggler=OptimizedToggler(count,env)            var i:USize = 1            toggler.togglin()            toggler.printn(env.args.contains("onlyopen", {(l,r)=>l==r}))        else            let toggler=Toggler(count,env)            var i:USize = 1            while i < count do                toggler.togglin(i)                i=i+1            end            toggler.printn(env.args.contains("onlyopen", {(l,r)=>l==r}))        end

## Pop11

unoptimized

lvars i;lvars doors = {% for i from 1 to 100 do false endfor %};for i from 1 to 100 do   for j from i by i to 100 do      not(doors(j)) -> doors(j);   endfor;endfor;;;; Print statefor i from 1 to 100 do   printf('Door ' >< i >< ' is ' ><            if doors(i) then 'open' else 'closed' endif, '%s\n');endfor;

optimized

for i to 100 do    lvars root = sqrt(i);    i; if root = round(root) then ' open' ><; else ' closed' ><; endif; =>endfor;

## PostScript

Bruteforce:
/doors [ 100 { false } repeat ] def 1 1 100 { dup 1 sub exch 99 {        dup doors exch get not doors 3 1 roll put} for } fordoors pstack
Shows:
[true false false true false false false false true false ...<90 doors later>... true]

## Potion

square=1, i=31 to 100(door):  if (door == square):    ("door", door, "is open") say    square += i    i += 2..

## PowerShell

### optimized

 1..10|%{"Door "+ $_*$_ + " is open"}

## Processing

Unoptimized:

boolean[] doors = new boolean; void setup() {  for (int i = 0; i < 100; i++) {    doors[i] = false;  }  for (int i = 1; i < 100; i++) {    for (int j = 0; j < 100; j += i) {      doors[j] = !doors[j];    }  }  println("Open:");  for (int i = 1; i < 100; i++) {    if (doors[i]) {      println(i);    }  }  exit();}
Output:
Open:
1
4
9
16
25
36
49
64
81

Unoptimized:

## R

Using a loop

doors_puzzle <- function(ndoors=100,passes=100) {    doors <- rep(FALSE,ndoors)    for (ii in seq(1,passes)) {        mask <- seq(0,ndoors,ii)        doors[mask] <- !doors[mask]	    }    return (which(doors == TRUE))} doors_puzzle()

optimized

x <- rep(1, 100)for (i in 1:100-1) {    x <- xor(x, rep(c(rep(0,i),1), length.out=100))}which(!x)

Using a **ply function

doors_puzzle <- function(ndoors=100,passes=100) {names(which(table(unlist(sapply(1:passes, function(X) seq(0, ndoors, by=X)))) %% 2 == 1))} doors_puzzle()

### Using Reduce

H=100f=rep(F,H)which(Reduce(function(d,n) xor(replace(f,seq(n,H,n),T),d), 1:H, f))
Output:
1   4   9  16  25  36  49  64  81 100


## Racket

 #lang racket ;; Applies fun to every step-th element of seq, leaving the others unchanged.(define (map-step fun step seq)  (for/list ([elt seq] [i (in-naturals)])    ((if (zero? (modulo i step)) fun values) elt))) (define (toggle-nth n seq)  (map-step not n seq)) (define (solve seq)  (for/fold ([result seq]) ([_ seq] [pass (in-naturals 1)])    (toggle-nth pass result))) (for ([door (solve (make-vector 101 #f))] [index (in-naturals)]      #:when (and door (> index 0)))  (printf "~a is open~%" index)) 

Optimized:

 #lang racket(for ([x (in-range 1 101)] #:when (exact-integer? (sqrt x)))  (printf "~a is open\n" x)) 

Unoptimized imperative, with graphic rendering:

 #lang slideshow(define-syntax-rule (vector-neg! vec pos)  (vector-set! vec pos (not (vector-ref vec pos)))) (define (make-doors)  (define doors (make-vector 100 #f))  (for* ([i 100] [j (in-range i 100 (add1 i))]) (vector-neg! doors j))  doors) (displayln (list->string (for/list ([d (make-doors)]) (if d #\o #\-)))) (define closed-door (inset (filled-rectangle 4 20) 2))(define open-door (inset (rectangle 4 20) 2)) (for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)])  (hc-append doors (if open? open-door closed-door))) 

Output:

## Raku

(formerly Perl 6)

### unoptimized

Works with: Rakudo version 2015.09"

### Here's a version using the cross meta-operator instead of a map:

 say "Door $_ is open" for 1..10 X** 2; This one prints both opened and closed doors: say "Door$_ is ", <closed open>[.sqrt == .sqrt.floor] for 1..100;

### verbose version, but uses ordinary components

Works with: Rakudo version 2016.07 Tom Legrady
 sub  output( @arr, $max ) { my$output = 1;    for 1..^$max ->$index {	if @arr[$index] { printf "%4d",$index;	    say '' if $output++ %% 10; } } say '';} sub MAIN ( Int :$doors = 100 ) {    my $doorcount =$doors + 1;    my @door[$doorcount] = 0 xx ($doorcount);     INDEX:    for 1...^$doorcount ->$index {        # flip door $index & its multiples, up to last door. # for ($index, * + $index ... *)[^$doors] -> $multiple { next INDEX if$multiple > $doors; @door[$multiple] =  @door[$multiple] ?? 0 !! 1; } } output @door,$doors+1;} 
Output:
$./100_doors.pl6 -doors=100 1 4 9 16 25 36 49 64 81  ## RapidQ  dim x as integer, y as integerdim door(1 to 100) as byte 'initialize arrayfor x = 1 to 100 : door(x) = 0 : next 'set door valuesfor y = 1 to 100 for x = y to 100 step y door(x) = not door(x) next xnext y 'print resultfor x = 1 to 100 if door(x) then print "Door " + str$(x) + " = open"next  while inkey$="":wendend  Output Door 1 = open Door 4 = open Door 9 = open Door 16 = open Door 25 = open Door 36 = open Door 49 = open Door 64 = open Door 81 = open Door 100 = open ## REBOL ### Unoptimized doors: array/initial 100 'closedrepeat i 100 [ door: at doors i forskip door i [change door either 'open = first door ['closed] ['open]]] ### Optimized doors: array/initial 100 'closedrepeat i 10 [doors/(i * i): 'open]  ## Red ### Unoptimized Red [ Purpose: "100 Doors Problem (Perfect Squares)" Author: "Barry Arthur" Date: "07-Oct-2016"]doors: make vector! [char! 8 100]repeat i 100 [change at doors i #"."] repeat i 100 [ j: i while [j <= 100] [ door: at doors j change door either #"O" = first door [#"."] [#"O"] j: j + i ]] repeat i 10 [ print copy/part at doors (i - 1 * 10 + 1) 10]  ## Retro :doors (n-) [ #1 repeat dup-pair n:square gt? 0; drop dup n:square n:put sp n:inc again ] do drop-pair ;#100 doors ## REXX ### the idiomatic way /*REXX pgm solves the 100 doors puzzle, doing it the hard way by opening/closing doors.*/parse arg doors . /*obtain the optional argument from CL.*/if doors=='' | doors=="," then doors=100 /*not specified? Then assume 100 doors*/ /* 0 = the door is closed. */ /* 1 = " " " open. */door.=0 /*assume all doors are closed at start.*/ do #=1 for doors /*process a pass─through for all doors.*/ do j=# by # to doors /* ··· every Jth door from this point.*/ door.j= \door.j /*toggle the "openness" of the door. */ end /*j*/ end /*#*/ say 'After ' doors " passes, the following doors are open:"say do k=1 for doors if door.k then say right(k, 20) /*add some indentation for the output. */ end /*k*/ /*stick a fork in it, we're all done. */ output when using the default input: After 100 passes, the following doors are open: 1 4 9 16 25 36 49 64 81 100  ### the shortcut way /*REXX pgm solves the 100 doors puzzle, doing it the easy way by calculating squares.*/parse arg doors . /*obtain the optional argument from CL.*/if doors=='' | doors=="," then doors=100 /*not specified? Then assume 100 doors*/say 'After ' doors " passes, the following doors are open:"say do #=1 while #**2 <= doors /*process easy pass─through (squares).*/ say right(#**2, 20) /*add some indentation for the output. */ end /*#*/ /*stick a fork in it, we're all done. */ {{out|output|text= is identical to the 1st REXX version. ## Ring Unoptimized doors = list(100)for i = 1 to 100doors[i] = falsenext For pass = 1 To 100 For door = pass To 100 if doors[door] doors[door] = false else doors[door] = true ok door += pass-1 NextNext For door = 1 To 100 see "Door (" + door + ") is " If doors[door] see "Open" else see "Closed" ok see nlNext Optimized doors = list(100)for i = 1 to 100doors[i] = falsenext For p = 1 To 10 doors[pow(p,2)] = TrueNext For door = 1 To 100 see "Door (" + door + ") is " If doors[door] see "Open" else see "Closed" ok see nlNext ## Ruby doors = Array.new(101,0)print "Open doors "(1..100).step(){ |i|(i..100).step(i) { |d| doors[d] = doors[d]^= 1 if i == d and doors[d] == 1 then print "#{i} " end }} Output: Open doors 1 4 9 16 25 36 49 64 81 100 unoptimized; Ruby-way class Door attr_reader :state def initialize @state = :closed end def close @state = :closed end def open @state = :open end def closed? @state == :closed end def open? @state == :open end def toggle if closed? then open else close end end def to_s @state.to_s endend doors = Array.new(100) { Door.new }1.upto(100) do |multiplier| doors.each_with_index do |door, i| door.toggle if (i + 1) % multiplier == 0 endend doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." } unoptimized n = 100Open = "open"Closed = "closed"def Open.toggle Closedenddef Closed.toggle Openenddoors = [Closed] * (n + 1)for mul in 1..n for x in (mul..n).step(mul) doors[x] = doors[x].toggle endenddoors.each_with_index do |b, i| puts "Door #{i} is #{b}" if i > 0end optimized n = 100(1..n).each do |i| puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}"end generic true/false, with another way of handling the inner loop demonstrating Range#step doors = [false] * 100100.times do |i| (i ... doors.length).step(i + 1) do |j| doors[j] = !doors[j] endendputs doors.map.with_index(1){|d,i| "Door #{i} is #{d ? 'open' : 'closed'}."} Output: Door 1 is open Door 2 is closed Door 3 is closed Door 4 is open Door 5 is closed Door 6 is closed Door 7 is closed Door 8 is closed Door 9 is open Door 10 is closed Door 11 is closed Door 12 is closed Door 13 is closed Door 14 is closed Door 15 is closed Door 16 is open Door 17 is closed Door 18 is closed Door 19 is closed Door 20 is closed Door 21 is closed Door 22 is closed Door 23 is closed Door 24 is closed Door 25 is open Door 26 is closed Door 27 is closed Door 28 is closed Door 29 is closed Door 30 is closed Door 31 is closed Door 32 is closed Door 33 is closed Door 34 is closed Door 35 is closed Door 36 is open Door 37 is closed Door 38 is closed Door 39 is closed Door 40 is closed Door 41 is closed Door 42 is closed Door 43 is closed Door 44 is closed Door 45 is closed Door 46 is closed Door 47 is closed Door 48 is closed Door 49 is open Door 50 is closed Door 51 is closed Door 52 is closed Door 53 is closed Door 54 is closed Door 55 is closed Door 56 is closed Door 57 is closed Door 58 is closed Door 59 is closed Door 60 is closed Door 61 is closed Door 62 is closed Door 63 is closed Door 64 is open Door 65 is closed Door 66 is closed Door 67 is closed Door 68 is closed Door 69 is closed Door 70 is closed Door 71 is closed Door 72 is closed Door 73 is closed Door 74 is closed Door 75 is closed Door 76 is closed Door 77 is closed Door 78 is closed Door 79 is closed Door 80 is closed Door 81 is open Door 82 is closed Door 83 is closed Door 84 is closed Door 85 is closed Door 86 is closed Door 87 is closed Door 88 is closed Door 89 is closed Door 90 is closed Door 91 is closed Door 92 is closed Door 93 is closed Door 94 is closed Door 95 is closed Door 96 is closed Door 97 is closed Door 98 is closed Door 99 is closed Door 100 is open  ## Run BASIC dim doors(100)print "Open doors ";for i = 1 to 100 for door = i to 100 step i doors(door) = (doors(door) <> 1) if i = door and doors(door) = 1 then print i;" "; next doornext i Output: Open doors 1 4 9 16 25 36 49 64 81 100 ## Rust fn main() { let mut door_open = [false; 100]; for pass in 1..101 { let mut door = pass; while door <= 100 { door_open[door - 1] = !door_open[door - 1]; door += pass; } } for (i, &is_open) in door_open.iter().enumerate() { println!("Door {} is {}.", i + 1, if is_open {"open"} else {"closed"}); }}} Declarative version of above: fn main() { let doors = vec![false; 100].iter_mut().enumerate() .map(|(door, door_state)| (1..100).into_iter() .filter(|pass| door % pass == 0) .map(|_| { *door_state = !*door_state; *door_state }) .last().unwrap()).collect::<Vec<_>>(); println!("{:?}", doors);}  Optimized version: (In this case the printing is the bottleneck so this version is not faster than the above one.) fn main() { let squares: Vec<_> = (1..10).map(|n| n*n).collect(); let is_square = |num| squares.binary_search(&num).is_ok(); for i in 1..100 { let state = if is_square(i) {"open"} else {"closed"}; println!("Door {} is {}", i, state); }} ultra-optimized: ported from Julia version fn main() { for i in 1u32..10u32{ println!("Door {} is open", i.pow(2)); }} ## S-BASIC $constant DOOR_OPEN = 1$constant DOOR_CLOSED = 0$constant MAX_DOORS = 100 var i, j = integerdim integer doors(MAX_DOORS) rem - all doors are initially closedfor i = 1 to MAX_DOORS  doors(i) = DOOR_CLOSEDnext i rem - pass through and flipfor i = 1 to MAX_DOORS  for j = i to MAX_DOORS step i    doors(j) = 1 - doors(j)  next jnext i rem - report resultsprint "The open doors are:"for i = 1 to MAX_DOORS  if doors(i) = DOOR_OPEN then     print i;next i end 
Output:
The open doors are:
1 4 9 16 25 36 49 64 81 100


## S-lang

variable door,    isOpen = Char_Type ,    pass; for (door = 1; door <= 100; door++) {    isOpen[door] = 0;} for (pass = 1; pass <= 100; pass++) {    for (door = pass; door <= 100; door += pass) {        isOpen[door] = not isOpen[door];    }} for (door = 1; door <= 100; door++) {    if (isOpen[door]) {        print("Door " + string(door) + ":open");    } else {        print("Door " + string(door) + ":close");    }}

## Salmon

Here's an unoptimized version:

variable open := <<(* --> false)>>;for (pass; 1; pass <= 100)    for (door_num; pass; door_num <= 100; pass)        open[door_num] := !(open[door_num]);;;iterate (door_num; [1...100])    print("Door ", door_num, " is ",          (open[door_num] ? "open.\n" : "closed.\n"));;

And here's an optimized one-line version:

iterate (x; [1...10]) { iterate (y; [(x-1)*(x-1)+1...x*x-1]) { print("Door ", y, " is closed.\n"); }; print("Door ", x*x, " is open.\n"); };

And a shorter optimized one-line version:

variable y:=1;for(x;1;x<101)"Door "~sprint(x)~" is "~(x==y*y?{++y;return"open";}:"closed")!;

## SAS

data _null_;   open=1;   close=0;   array Door{100};   do Pass = 1 to 100;      do Current = Pass to 100 by Pass;         if Door{Current} ne open             then Door{Current} = open;            else Door{Current} = close;      end;   end;   NumberOfOpenDoors = sum(of Door{*});   put "Number of Open Doors:  " NumberOfOpenDoors; run;

## Sather

class MAIN is  main is    pass, door :INT;    doors :ARRAY{BOOL} := #(100);    loop       doors[0.upto!(99)] := false;    end;    pass := 0;    loop while!(pass < 100);      door := pass;      loop while! (door < 100);        doors[door] := ~doors[door];	door := door + pass + 1      end;      pass := pass + 1;    end;    loop      door := 0.upto!(99);      #OUT + (door+1) + " " + doors[door] + "\n";    end;  end;end;

## Scala

for { i <- 1 to 100      r = 1 to 100 map (i % _ == 0) reduceLeft (_^_)                     } println (i +" "+ (if (r) "open" else "closed"))

The map operation maps each door (i) to a boolean sequence of toggles, one for each pass: true toggles, false leaves the same.

The reduceLeft method combines all the toggles sequentially, using the XOR operator.

And then we just need to output the result.

I made a version that optional accepts an argument for the number of doors. It is also a little more a ‘classical’ solution:

 def openDoors(length : Int = 100) = {    var isDoorOpen = new Array[Boolean](length)     for (i <- 0 until length) {        for (j <- i until length by i + 1) {            isDoorOpen(j) ^= true        }    }    isDoorOpen} val doorState  = scala.collection.immutable.Map(false -> "closed", true -> "open")val isDoorOpen = openDoors() for (doorNo <- 0 until isDoorOpen.length) {    println("Door %d is %s".format(doorNo + 1, doorState(isDoorOpen(doorNo))))} 

I created the function openDoors which gives back an array signifying if a door is open and optional accepts an argument for the number of doors. (I like to make things general.) I call the function and use the result to display the status of the doors.

"Optimized" version:

val o = 1 to 10 map (i => i * i)println("open: " + o)println("closed: " + (1 to 100 filterNot o.contains))

## Scheme

unoptimized

(define *max-doors* 100) (define (show-doors doors)  (let door ((i 0)             (l (vector-length doors)))    (cond ((= i l)            (newline))          (else            (printf "~nDoor ~a is ~a"                    (+ i 1)                    (if (vector-ref doors i) "open" "closed"))           (door (+ i 1) l))))) (define (flip-doors doors)  (define (flip-all i)    (cond ((> i *max-doors*) doors)          (else            (let flip ((idx (- i 1)))             (cond ((>= idx *max-doors*)                     (flip-all (+ i 1)))                    (else                     (vector-set! doors idx (not (vector-ref doors idx)))                    (flip (+ idx i))))))))  (flip-all 1)) (show-doors (flip-doors (make-vector *max-doors* #f)))

optimized

(define (optimised-flip-doors doors)  (define (flip-all i)    (cond ((> i (floor (sqrt *max-doors*))) doors)          (else            (vector-set! doors (- (* i i) 1) #t)           (flip-all (+ i 1)))))  (flip-all 1)) (show-doors (optimised-flip-doors (make-vector *max-doors* #f)))

the 3rd version

(define (N_doors N)  (define (init)    (define (str n)      (if (> n N) '() (cons 0 (str (+ 1 n)))))    (str 1))  (define (toggle x str)    (define (s n lis)      (define (revert x)        (if (eq? x 0) 1 0))      (cond ((null? lis) '())          ((zero? (remainder n x)) (cons (revert (car lis)) (s (+ n 1) (cdr lis))))          (else (cons (car lis) (s (+ n 1) (cdr lis))))))    (s 1 str))  (define (iterate x lis)    (if (> x N) lis (iterate (+ x 1) (toggle x lis))))  (iterate 1 (init)))(N_doors 100)

Output of the 3rd version: 1 represents open, 0 represents closed.

(1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)


## Scilab

Translation of: Octave
doors=zeros(1,100);for i = 1:100  for j = i:i:100    doors(j) = ~doors(j);  endendfor i = 1:100  if ( doors(i) )    s = "open";  else    s = "closed";  end  printf("%d %s\n", i, s);end
Output:
1 open
2 closed
3 closed
4 open
5 closed
6 closed
7 closed
8 closed
9 open
10 closed
11 closed
12 closed
13 closed
14 closed
15 closed
16 open
17 closed
18 closed
19 closed
20 closed
21 closed
22 closed
23 closed
24 closed
25 open
26 closed
27 closed
28 closed
29 closed
30 closed
31 closed
32 closed
33 closed
34 closed
35 closed
36 open
37 closed
38 closed
39 closed
40 closed
41 closed
42 closed
43 closed
44 closed
45 closed
46 closed
47 closed
48 closed
49 open
50 closed
51 closed
52 closed
53 closed
54 closed
55 closed
56 closed
57 closed
58 closed
59 closed
60 closed
61 closed
62 closed
63 closed
64 open
65 closed
66 closed
67 closed
68 closed
69 closed
70 closed
71 closed
72 closed
73 closed
74 closed
75 closed
76 closed
77 closed
78 closed
79 closed
80 closed
81 open
82 closed
83 closed
84 closed
85 closed
86 closed
87 closed
88 closed
89 closed
90 closed
91 closed
92 closed
93 closed
94 closed
95 closed
96 closed
97 closed
98 closed
99 closed
100 open


## Scratch

Scratch is a visual programming language. Click the link, then "see inside" to see the code.

Output: 100 indications that "Door ___ is _____," where doors with perfect square indices are open and the rest are closed.

## Seed7

unoptimized

$include "seed7_05.s7i"; const proc: main is func local var array boolean: doorOpen is 100 times FALSE; var integer: pass is 0; var integer: index is 0; var array[boolean] string: closedOrOpen is [boolean] ("closed", "open"); begin for pass range 1 to 100 do for key index range doorOpen do if index rem pass = 0 then doorOpen[index] := not doorOpen[index]; end if; end for; end for; for key index range doorOpen do write(index lpad 3 <& " is " <& closedOrOpen[doorOpen[index]] rpad 7); if index rem 5 = 0 then writeln; end if; end for; end func; optimized $ include "seed7_05.s7i"; const proc: main is func  local    var integer: index is 0;    var integer: number is 0;    var array[boolean] string: closedOrOpen is [boolean] ("closed", "open");  begin    for index range 1 to 100 do      number := sqrt(index);      write(index lpad 3 <& " is " <& closedOrOpen[number**2 = index] rpad 7);      if index rem 5 = 0 then        writeln;      end if;    end for;  end func;

Output of both programs:

  1 is open     2 is closed   3 is closed   4 is open     5 is closed
6 is closed   7 is closed   8 is closed   9 is open    10 is closed
11 is closed  12 is closed  13 is closed  14 is closed  15 is closed
16 is open    17 is closed  18 is closed  19 is closed  20 is closed
21 is closed  22 is closed  23 is closed  24 is closed  25 is open
26 is closed  27 is closed  28 is closed  29 is closed  30 is closed
31 is closed  32 is closed  33 is closed  34 is closed  35 is closed
36 is open    37 is closed  38 is closed  39 is closed  40 is closed
41 is closed  42 is closed  43 is closed  44 is closed  45 is closed
46 is closed  47 is closed  48 is closed  49 is open    50 is closed
51 is closed  52 is closed  53 is closed  54 is closed  55 is closed
56 is closed  57 is closed  58 is closed  59 is closed  60 is closed
61 is closed  62 is closed  63 is closed  64 is open    65 is closed
66 is closed  67 is closed  68 is closed  69 is closed  70 is closed
71 is closed  72 is closed  73 is closed  74 is closed  75 is closed
76 is closed  77 is closed  78 is closed  79 is closed  80 is closed
81 is open    82 is closed  83 is closed  84 is closed  85 is closed
86 is closed  87 is closed  88 is closed  89 is closed  90 is closed
91 is closed  92 is closed  93 is closed  94 is closed  95 is closed
96 is closed  97 is closed  98 is closed  99 is closed 100 is open


## SenseTalk

 put false repeated 100 times as a list into Doors100 repeat 1 to 100	set step to it	repeat step to 100 by step 		set newValue to not item it of Doors100		set item it of Doors100 to newValue	end repeatend repeat put the counter for each item of Doors100 which is true 

Output:

(1,4,9,16,25,36,49,64,81,100)

## SequenceL

Unoptimized

 import <Utilities/Sequence.sl>; main:=	let		doors := flipDoors(duplicate(false, 100), 1);		open[i] := i when doors[i];	in		open; flipDoors(doors(1), count) :=	let		newDoors[i] := not doors[i] when i mod count = 0 else doors[i];	in		doors when count >= 100 else flipDoors(newDoors, count + 1); 

Optimized

 main := flipDoors(, 2); flipDoors(openDoors(1), i) :=	openDoors when i * i >= 100 else flipDoors(openDoors ++ [i * i], i + 1); 

## SETL

Unoptimized

program hundred_doors; const toggle := {['open', 'closed'], ['closed', 'open']}; doorStates := ['closed'] * 100; (for interval in [1..100])  doorStates := [if i mod interval = 0 then                    toggle(prevState) else                    prevState end:                 prevState = doorStates(i)];end; (for finalState = doorStates(i))  print('door', i, 'is', finalState);end; end program;

If 'open' weren't a reserved word, we could omit the single quotes around it.

Optimized Exploits the fact that squares are separated by successive odd numbers. Use array replication to insert the correct number of closed doors in between the open ones.

program hundred_doors; doorStates := (+/ [['closed'] * oddNum with 'open': oddNum in [1,3..17]]); (for finalState = doorStates(i))  print('door', i, 'is', finalState);end; end program;

## SheerPower 4GL

 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%!         I n i t i a l i z a t i o n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%doors% = 100 dim doorArray?(doors%) !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%!         M a i n   L o g i c   A r e a!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Initialize Arrayfor index% = 1 to doors%  doorArray?(index%) = falsenext index% // Execute routinetoggle_doors // Print resultsfor index% = 1 to doors%  if doorArray?(index%) = true then print index%, ' is open'next index%  stop  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%!         R o u t i n e s!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%routine toggle_doors  for index_outer% = 1 to doors%    for index_inner% = 1 to doors%      if mod(index_inner%, index_outer%) = 0 then        doorArray?(index_inner%) = not doorArray?(index_inner%)       end if    next index_inner%  next index_outer%end routine  end 

## Sidef

Unoptimized

var doors = [] { |pass|    { |i|        if (pass divides i) {            doors[i] := false -> not!        }    } << 1..100} << 1..100 { |i|    say ("Door %3d is %s" % (i, doors[i] ? 'open' : 'closed'))} << 1..100

Optimized

{ |i|    "Door %3d is %s\n".printf(i, <closed open>[i.is_sqr])} << 1..100

## Simula

BEGIN    INTEGER LIMIT = 100, door, stride;    BOOLEAN ARRAY DOORS(1:LIMIT);    TEXT intro;     FOR stride := 1 STEP 1 UNTIL LIMIT DO        FOR door := stride STEP stride UNTIL LIMIT DO            DOORS(door) := NOT DOORS(door);     intro :- "All doors closed but ";    FOR door := 1 STEP 1 UNTIL LIMIT DO        IF DOORS(door) THEN BEGIN            OUTTEXT(intro); OUTINT(door, 0); intro :- ", "        END;    OUTIMAGEEND.
Output:
All doors closed but 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

## Slate

Unoptimized

define: #a -> (Array newSize: 100).a infect: [| :_ | False]. a keysDo: [| :pass |  pass to: a indexLast by: pass do: [| :door |    a at: door infect: #not er]]. a keysAndValuesDo: [| :door :isOpen |  inform: 'door #' ; door ; ' is ' ; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].

Optimized

define: #a -> (Array newSize: 100).a infect: [| :_ | False]. 0 below: 10 do: [| :door | a at: door squared put: True].a keysAndValuesDo: [| :door :isOpen |  inform: 'door #' ; door ; ' is ' ; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].

## Smalltalk

Works with: GNU Smalltalk

Unoptimized

|a|a := Array new: 100 .1 to: 100 do: [ :i | a at: i put: false ]. 1 to: 100 do: [ :pass |  pass to: 100 by: pass do: [ :door |    a at: door put: (a at: door) not .  ]]. "output"1 to: 100 do: [ :door |   ( 'door #%1 is %2' %     { door . (a at: door) ifTrue: [ 'open' ] ifFalse: [ 'closed' ] } ) displayNl]

Optimized

|a|a := (1 to: 100) collect: [ :x | false ].1 to: 10 do: [ :i | a at: (i squared) put: true ].1 to: 100 do: [ :i |   ( 'door #%1 is %2' % { i .            (a at: i) ifTrue: [ 'open' ]                      ifFalse: [ 'closed' ] }   ) displayNl]
Works with: Squeak Smalltalk

Unoptimized, using Morphs

 | m w h smh smw delay closedDoor border subMorphList | closedDoor := Color black.border := Color veryLightGray.delay := Delay forMilliseconds: 50.w := World bounds corner x.h := (World bounds corner y) / 2.smw := w/100.smh := h/2. m := BorderedMorph new position: 0@h.m height: smh; width: w; borderColor: border.m color: Color veryLightGray. 1 to: 100 do: [ :pos || sm |	sm := BorderedMorph new height: smh ; width: smw ; 		borderColor: border; color: closedDoor; 		position: (smw*pos)@h.	m addMorph: sm asElementNumber: pos]. m openInWorld.delay wait.subMorphList := m submorphs."display every step"[1 to: 100 do: [ :step |	step to: 100 by: step do: [ :pos | | subMorph |		subMorph := subMorphList at: pos.		subMorph color: subMorph color negated.		delay wait]]] fork.

## smart BASIC

x=1!y=3!z=0PRINT "Open doors: ";x;" ";DO    z=x+y    PRINT z;" ";    x=z    y=y+2UNTIL z>=100END

## SNOBOL4

unoptimized

 		DEFINE('PASS(A,I),O')		:(PASS.END)PASS		O = 0PASS.LOOP	O = O + I		EQ(A<O>,1)			:S(PASS.1)F(PASS.0)PASS.0		A<O> = 1			:S(PASS.LOOP)F(RETURN)PASS.1		A<O> = 0			:S(PASS.LOOP)F(RETURN)PASS.END MAIN		D = ARRAY(100,0)		I = 0 MAIN.LOOP	I = LE(I,100) I + 1		:F(OUTPUT)		PASS(D,I)			:(MAIN.LOOP) OUTPUT		I = 1 ; OPEN = 'Opened doors are: 'OUTPUT.LOOP	OPEN = OPEN EQ(D<I>,1) " " I		I = LE(I,100) I + 1		:S(OUTPUT.LOOP)F(OUTPUT.WRITE)OUTPUT.WRITE	OUTPUT = OPEN END

A run of this using CSNOBOL4 looks like this:

$snobol4 100doors.sno The Macro Implementation of SNOBOL4 in C (CSNOBOL4) Version 1.3+ by Philip L. Budne, January 23, 2011 SNOBOL4 (Version 3.11, May 19, 1975) Bell Telephone Laboratories, Incorporated No errors detected in source program Opened doors are: 1 4 9 16 25 36 49 64 81 100 Normal termination at level 0 100doors.sno:18: Last statement executed was 19  (There are command flags to remove the header and the summary, but these have been left in to keep the original SNOBOL4 experience intact.) optimized  MAIN D = ARRAY(100,0) I = 1 MAIN.LOOP LE(I, 10) :F(OUTPUT) D<I ** 2> = 1 I = I + 1 :(MAIN.LOOP) OUTPUT I = 1 ; O = 'Opened doors are: 'OUTPUT.LOOP O = O EQ(D<I>,1) " " I I = LE(I,100) I + 1 :S(OUTPUT.LOOP)F(OUTPUT.WRITE)OUTPUT.WRITE OUTPUT = OEND  The output of this version is almost identical to the above. ## Sparkling unoptimized /* declare the variables */var isOpen = {};var pass, door; /* initialize the doors */for door = 0; door < 100; door++ { isOpen[door] = true;} /* do the 99 remaining passes */for pass = 1; pass < 100; ++pass { for door = pass; door < 100; door += pass+1 { isOpen[door] = !isOpen[door]; }} /* print the results */var states = { true: "open", false: "closed" };for door = 0; door < 100; door++ { printf("Door #%d is %s.\n", door+1, states[isOpen[door]]);} optimized /* declare the variables */var door_sqrt = 1;var door; /* print the perfect square doors as open */for door = 0; door < 100; door++ { if (door_sqrt*door_sqrt == door+1) { printf("Door #%d is open.\n", door+1); door_sqrt ++; } else { printf("Door #%d is closed.\n", door+1); }} ## Spin Works with: BST/BSTC Works with: FastSpin/FlexSpin Works with: HomeSpun Works with: OpenSpin con _clkmode = xtal1+pll16x _clkfreq = 80_000_000 obj ser : "FullDuplexSerial.spin" pub init ser.start(31, 30, 0, 115200) doors waitcnt(_clkfreq + cnt) ser.stop cogstop(0) var byte door ' waste one byte by using only door[1..100] pri doors | i,j repeat i from 1 to 100 repeat j from i to 100 step i not door[j] ser.str(string("Open doors: ")) repeat i from 1 to 100 if door[i] ser.dec(i) ser.tx(32) ser.str(string(13,10)) Output: Open doors: 1 4 9 16 25 36 49 64 81 100  ## SQL optimized  DECLARE @sqr INT, @i INT, @door INT; SELECT @sqr =1, @i = 3, @door = 1; WHILE(@door <=100)BEGIN IF(@door = @sqr) BEGIN PRINT 'Door ' + RTRIM(CAST(@door AS CHAR)) + ' is open.'; SET @sqr= @sqr+@i; SET @i=@i+2; END ELSE BEGIN PRINT 'Door ' + RTRIM(CONVERT(CHAR,@door)) + ' is closed.'; ENDSET @door = @door + 1END  ## SQL PL Works with: Db2 LUW With SQL only:  --#SET TERMINATOR @ SET SERVEROUTPUT ON @ BEGIN DECLARE TYPE DOORS_ARRAY AS BOOLEAN ARRAY ; DECLARE DOORS DOORS_ARRAY; DECLARE I SMALLINT; DECLARE J SMALLINT; DECLARE STATUS CHAR(10); DECLARE SIZE SMALLINT DEFAULT 100; -- Initializes the array, with all spaces (doors) as false (closed). SET I = 1; WHILE (I <= SIZE) DO SET DOORS[I] = FALSE; SET I = I + 1; END WHILE; -- Processes the doors. SET I = 1; WHILE (I <= SIZE) DO SET J = 1; WHILE (J <= SIZE) DO IF (MOD(J, I) = 0) THEN IF (DOORS[J] = TRUE) THEN SET DOORS[J] = FALSE; ELSE SET DOORS[J] = TRUE; END IF; END IF; SET J = J + 1; END WHILE; SET I = I + 1; END WHILE; -- Prints the final status o the doors. SET I = 1; WHILE (I <= SIZE) DO SET STATUS = (CASE WHEN (DOORS[I] = TRUE) THEN 'OPEN' ELSE 'CLOSED' END); CALL DBMS_OUTPUT.PUT_LINE('Door ' || I || ' is '|| STATUS); SET I = I + 1; END WHILE;END @  Output: db2 [email protected] db2 => BEGIN ... db2 (cont.) => END @ DB20000I The SQL command completed successfully. Door 1 is OPEN Door 2 is CLOSED Door 3 is CLOSED Door 4 is OPEN Door 5 is CLOSED Door 6 is CLOSED Door 7 is CLOSED Door 8 is CLOSED Door 9 is OPEN Door 10 is CLOSED Door 11 is CLOSED Door 12 is CLOSED Door 13 is CLOSED Door 14 is CLOSED Door 15 is CLOSED Door 16 is OPEN Door 17 is CLOSED Door 18 is CLOSED Door 19 is CLOSED Door 20 is CLOSED Door 21 is CLOSED Door 22 is CLOSED Door 23 is CLOSED Door 24 is CLOSED Door 25 is OPEN Door 26 is CLOSED Door 27 is CLOSED Door 28 is CLOSED Door 29 is CLOSED Door 30 is CLOSED Door 31 is CLOSED Door 32 is CLOSED Door 33 is CLOSED Door 34 is CLOSED Door 35 is CLOSED Door 36 is OPEN Door 37 is CLOSED Door 38 is CLOSED Door 39 is CLOSED Door 40 is CLOSED Door 41 is CLOSED Door 42 is CLOSED Door 43 is CLOSED Door 44 is CLOSED Door 45 is CLOSED Door 46 is CLOSED Door 47 is CLOSED Door 48 is CLOSED Door 49 is OPEN Door 50 is CLOSED Door 51 is CLOSED Door 52 is CLOSED Door 53 is CLOSED Door 54 is CLOSED Door 55 is CLOSED Door 56 is CLOSED Door 57 is CLOSED Door 58 is CLOSED Door 59 is CLOSED Door 60 is CLOSED Door 61 is CLOSED Door 62 is CLOSED Door 63 is CLOSED Door 64 is OPEN Door 65 is CLOSED Door 66 is CLOSED Door 67 is CLOSED Door 68 is CLOSED Door 69 is CLOSED Door 70 is CLOSED Door 71 is CLOSED Door 72 is CLOSED Door 73 is CLOSED Door 74 is CLOSED Door 75 is CLOSED Door 76 is CLOSED Door 77 is CLOSED Door 78 is CLOSED Door 79 is CLOSED Door 80 is CLOSED Door 81 is OPEN Door 82 is CLOSED Door 83 is CLOSED Door 84 is CLOSED Door 85 is CLOSED Door 86 is CLOSED Door 87 is CLOSED Door 88 is CLOSED Door 89 is CLOSED Door 90 is CLOSED Door 91 is CLOSED Door 92 is CLOSED Door 93 is CLOSED Door 94 is CLOSED Door 95 is CLOSED Door 96 is CLOSED Door 97 is CLOSED Door 98 is CLOSED Door 99 is CLOSED Door 100 is OPEN  ## Standard ML  datatype Door = Closed | Opened fun toggle Closed = Opened | toggle Opened = Closed fun pass (steps, doors) = List.mapi (fn (k, door) => if (k+1) mod steps = 0 then toggle door else door) doors (* [1..n] *)fun runs n = List.tabulate (n, fn k => k+1) fun run n = let val initialdoors = List.tabulate (n, fn _ => Closed) val runs = runs n in foldl pass initialdoors runs end fun opened_doors n = List.mapPartiali (fn (k, Closed) => NONE | (k, Opened) => SOME (k+1)) (run n)  Output: - opened_doors 100; val it = [1,4,9,16,25,36,49,64,81,100] : int list  ## Stata clearset obs 100gen doors=0gen index=_nforvalues i=1/100 { quietly replace doors=!doors if mod(_n,i')==0}list index if doors, noobs noheader +-------+ | 1 | | 4 | | 9 | | 16 | | 25 | |-------| | 36 | | 49 | | 64 | | 81 | | 100 | +-------+ ## SuperCollider (var n = 100, doors = false ! n;var pass = { |j| (0, j .. n-1).do { |i| doors[i] = doors[i].not } };(1..n-1).do(pass);doors.selectIndices { |open| open }; // all are closed except [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ]) ## Swift unoptimized /* declare enum to identify the state of a door */enum DoorState : String { case Opened = "Opened" case Closed = "Closed"} /* declare list of doors state and initialize them */var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed) /* do the 100 passes */for i in 1...100 { /* map on a strideTo instance to only visit the needed doors on each iteration */ map(stride(from: i - 1, to: 100, by: i)) { doorsStateList[$0] = doorsStateList[\$0] == .Opened ? .Closed : .Opened    }} /* print the results */for (index, item) in enumerate(doorsStateList) {    println("Door \(index+1) is \(item.rawValue)")}

optimized

/* declare enum to identify the state of a door */enum DoorState : String {    case Opened = "Opened"    case Closed = "Closed"} /* declare list of doors state and initialize them */var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed) /* set i^2 doors to opened */var i = 1do {    doorsStateList[(i*i)-1] = DoorState.Opened    ++i} while (i*i) <= doorsStateList.count /* print the results */for (index, item) in enumerate(doorsStateList) {    println("Door \(index+1) is \(item.rawValue)")}`