/* * There are one hundred closed lockers in a hallway. * A man begins by opening all one hundred lockers. * Next, he closes every second locker. * Then he goes to every third locker and closes it if it is open or opens it if it is closed * (e.g., he toggles every third locker). * After his one hundredth pass in the hallway, in which he toggles only locker number one hundred, * how many lockers are open? */ /* * Below same solution can be applied for the switches question also. */ public class Doors { public static void main(String[] args) { int doorsN = 1000; boolean[] doors = new boolean[doorsN]; for(int i = 0; i < doorsN; i++) { doors[i] = false; } int round = 1; while(round <= doorsN) { for(int i = 0; i < doorsN; i++) { if((i+1)%round == 0) { if(doors[i]) doors[i] = false; else doors[i] = true; } } round++; } for(int i = 0; i < doorsN; i++) { if(doors[i]) { System.out.println(i+1); } } } }
Much faster way:- public class Doors { public static void main(String[] args) { int doorsN = 1000; int round = 0; while((++round)*round <= doorsN) System.out.println(round*round); } }