Thursday, February 21, 2013

Puzzle

I saw this puzzle on the Web:

pzl0

Simple test? More like ambiguous test.

You can compute the answer in your head. But let’s enter the numbers and operations into a calculator. The result of each operation is shown in square brackets:

So “D”, 56, is the correct answer. Or is it? The fact that the number 56 is so easily obtained tells us that it can’t be the complete answer. If it were, then everyone would solve the puzzle in seconds.

Let’s treat the numbers and math operations as a line of computer code. After lines of computer code are created (coded) by a programmer, a software tool called a compiler converts the typed code into an executable program. Compilers prioritize multiplication and division over addition and subtraction. Higher priority operations are calculated first. If we enclose the higher priority (multiplication and division) operations in parentheses and perform those operations first, we are doing what the compiler does:

So “C”, 50, is a correct answer. But wait. A compiler gives priority to multiplication and division, but that doesn’t mean we have to do the same. We can choose to give priority to addition and subtraction. If we do, we will get:

So “A”, 0, is also a correct answer.

We know answers A, C, and D can be obtained from the formula. It is reasonable at this point to suspect all the answers are correct. What about answer B? Do you see any way to solve the formula for a result of 8? If you want to try, go ahead. I’ll hide the solution below the break while you think about it.

Here is the solution for answer B:

Neither a calculator nor a compiler would group the numbers this way. But then, the calculator and the compiler don’t know what you’re trying to do. For a particular formula, this could very well be the correct way to group the numbers.

So all four answers are possible correct answers. This puzzle demonstrates a very real pitfall for programmers and engineers. This simple formula can give at least 4 different results. Usually, the programmer is intending one result. Parentheses tell the computer how to prioritize the math operations. Without parentheses in the proper places, we may get a wrong “right” answer. And we might not know about our error until the moon lander that is navigating by our math formula smacks into the moon at two miles per second. Oops. Before we launch that moon lander, let’s double-check our parentheses!

No comments: