Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created September 17, 2020 21:50
Show Gist options
  • Save davepkennedy/214845e94ec499078c1842c538026892 to your computer and use it in GitHub Desktop.
Save davepkennedy/214845e94ec499078c1842c538026892 to your computer and use it in GitHub Desktop.
public class SwitchFlipping {
public static void main (String[] args) {
doSlowWay();
doFastWay();
}
private static boolean isSquare (int i) {
int s = (int)Math.sqrt(i);
return (s*s) == i;
}
private static void doFastWay() {
for (int i = 0; i < 100; i++) {
if (isSquare(i)) {
System.out.println("Switch " + i + " is on");
}
}
}
private static void doSlowWay() {
boolean[] switches = new boolean[100];
for (int i = 1; i < switches.length; i++) {
for (int j = 0; j < switches.length; j += i) {
switches[j] = !switches[j];
}
}
for (int i = 0; i < switches.length; i++) {
if (switches[i]) {
System.out.println("Switch " + i + " is on");
}
}
}
}
@davepkennedy
Copy link
Author

Flipping switches or opening locker doors.
Open all the doors/flip all the switches, then do every 2nd, 3rd, 4th, etc. Which doors are still open/switches still on at the end.
Square numbers have an odd number of factors; 9 -> 1, 3, 9
Not square number have an even number of factors; 10 -> 1, 2, 5, 10
Square numbers will consequently still be on/open at the end of the process while all other numbers will have closed/turned off.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment