Keep it Simple, Stooopid

I fell for a trick question today when demonstrating my technical ability. I don’t feel too bad about it – it was all in good spirit, and it was designed to catch people out (and it was first thing on Monday morning…). The question was deceptively simple.

“What’s your most efficient way of printing out all the odd numbers between 1 and 1000?”

Immediately I gave the same answer as – according to the Askee – everyone else: with a loop and the mod operator. Pseudo code:

for(int i = 0; i <= 1000; i++)
	if(i % 2 != 0) Console.WriteLine(i);

Simple, obvious, and pretty efficient, no? With a grin the Askee wrote “i+2” on the piece of paper, and left it at that. After a moment my eyes went wide and I’m sure I physically slapped my forehead when the realisation hit. While the answer above is how 99.99% of developers would answer the question, it’s over-engineered. This would have been a much simpler solution:

for(int i = 1; i <= 1000; i = i + 2)

Each odd number is two more than the last one. Duh…

In the follow-up discussion we talked about how most developers tend to over-complicate things almost on instinct. Our solutions may be correct and (usually) robust, but often if we step back a moment there would be a much more straightforward way to solve the problem. So I may have felt stupid for a moment, but it led to an interesting discussion about the nature of programmers, where hopefully I saved face!