18 Feb 2011

1000 Lockers Problem

My sister’s friend proposed a logical/mathematical puzzle today that I decided to solve algorithmically. There may be a more efficient way to solve it, and after figuring it out with the program, I found a better way to think about the problem, but I wanted to post the code that I wrote this afternoon to find the answer.

Here is the puzzle: Imagine 1000 lockers in a school. They all start out closed. There are also 1000 people, each given a number corresponding to one of the 1000 lockers. They then go to their locker number (e.g. Locker #14) and each one of it’s factors (e.g. 7, 2, 1) and open it, or close it (if someone else had already opened it). The question is: How many lockers will be open once every person (1 through 1000) has opened or closed their locker number and every factor of that number.

I’ll post the answer at the end in case you want to solve it for yourself. Here is my code:

The answer is 31. It is the number of perfect squares from 1 to 1000.