C++: 100 Doors Problem

Bjarne-stroustrup
 

Problem: You have 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, …). The third time, every 3rd door (door #3, #6, #9, …), etc, until you only visit the 100th door.

Question: What state are the doors in after the last pass? Which are open, which are closed?

Unoptimized:

#include <iostream>

int main()
{
	bool is_open[100] = { 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;
}

Content is available under GNU Free Documentation License 1.2.

SOURCE