From Coding Horror - The Nonprogramming Programmer comments
You have the numbers 123456789, in that order. Between each number, you must insert either nothing, a plus sign, or a multiplication sign, so that the resulting expression equals 2001. Write a program that prints all solutions.
$numbers = "123456789";
$goal = 2001;
evalMath($numbers[0], substr($numbers, 1), $goal);
function evalMath($statement, $remaining, $goal){
if(empty($remaining)){
eval("\$solution = $statement;");
if($solution == $goal)
printf("<div class=\"solution\">%s = %s</div>", $statement, $solution);
}
else
foreach(array("", "+", "-", "*", "/") as $op)
evalMath($statement . $op . $remaining[0], substr($remaining, 1), $goal);
}
(It might take a minute. Be patient. Some values have no answers.)