2435 - Number Games

2435 - Number Games
Africa and the Middle East - South Africa - 2006/2007
You have been chosen to appear on a certain game show. One of the events in this game show requires you to
discover a way in which to combine up to six different numbers, using simple arithmetic, to arrive at a target
value. For example, you will be given the sequence
75 50 9 7 6 3
from which you have to form the target value of 234.
One possible solution to this particular sequence would be 3 * 75 + 9 = 234. The following rules are used to
evaluate this expression:
1. Each input number may be used once, at most.
2. Evaluation is cumulative, and strictly left-to-right; there is no operator precedence.
3. You may use addition (+), subtraction (-), multiplication (*), and division (/).
4. Subtraction is only allowed if the result is non-negative.
5. Division is only allowed if the remainder is zero.
Using these rules, another possibility would have been 6 * 7 - 3 * 9 * 50/75 = 234. Note that in conventional
arithmetic, this translates into ((((6 * 7) - 3) * 9) * 50)/75. This is the only valid evaluation order for this
sequence.
You have to develop a program that will give you an advantage in this game, however, you are not a complete
cheat. Thus, your program must work out what the fewest number of input numbers is that can be used to
form an expression that yields the target value.
Note that the number of mathematical operators you require will always be one less than the number of input
numbers you use.
For the example above, we already know of two solutions: one using only 3 input numbers, and the other
using all 6 input numbers. Incidentally, the shortest possible solution for this sequence requires only 3
numbers, thus the output of your algorithm will be the number 3.
Input
Your input contains an arbitrary number of records, each record consisting of exactly 7 integers. The format is
as follows:
< target > < number 1 > < number 2 >...< number 6 >
The end of input is indicated by line containing a single `0'.
2435 - Number Games
1/2
Output
For each input record, you must print out a single integer, indicating the minimum number of input numbers
required to build an equation that results in the target number. Each such output corresponding to an input
record should appear on its own line.
Sample Input
234 75 50 9 7 6 3
0
Sample Output
3
South Africa 2006-2007
2435 - Number Games
2/2