Problem

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.

Solution (PHP)


  $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);
  }
  

Example

The value the statements should evaluate to:

Results for 2017

(It might take a minute. Be patient. Some values have no answers.)

12+345*6+7-8*9 = 2017
12+345*6-7*8-9 = 2017
1+2*34*5*6-7-8-9 = 2017