Devin Üner

Coin flipping

A friend sent me this puzzle:

You place 100 coins heads up in a row and number them by position, the coin all the way on the left is No. 1, and the one on the rightmost edge is No. 100. Next, for every number N, from 1 to 100, you flip over every coin whose position is a multiple of N.

For example, first you’ll flip over all the coins, because every number is a multiple of 1. Then you’ll flip over all the even-numbered coins, because they’re multiples of 2. Then you’ll flip coins No. 3, 6, 9, 12 … and so on. What do the coins look like when you’re done? Specifically, which coins are heads down?

In the end, note that only numbers which can be expressed as X^2 (1, 4, 9, 16…) are face down, as only they have an odd number of factors. Below is a little visualization of the problem.

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

Overall the code for this isn’t too complex, it’s only around 30 lines of Javascript. Step one is to initialize everything we will need later on:

var array = [];
var time_delay = 1;

Array is the array of names of all the cells whose color we want to switch. time_delay keeps track of the time delay, as will be explained later on.

for(var i = 1; i <= 100; i++){
	for(var j = 0; j < 100; j++){
		if((j + 1) % i == 0){
			var name = ((Math.floor(j / 10)).toString() + (j % 10).toString());
			array.push(name);
			setTimeout(color_next, time_delay * 100);
			time_delay = time_delay + 1;
		}
	}
}

This iterates over every number from 1 to 100, and then checks if each cell is a multiple of that number. If it is, it adds it to our array.

Next we just loop over the array and every 100ms we flip the color of the cell at the top of the stack.

color_next(){
	name = array.shift();
	var myElement = document.getElementById(name);
	if(myElement.style.backgroundColor == "red"){
		myElement.style.backgroundColor = "white";
	} else {
		myElement.style.backgroundColor = "red";
	}
}