I'm trying to help my son solve a math problem. This seems like a good opportunity to expose him to some programming. I can see the recursive solution but perhaps an iterative one would be easier to explain. The language he has learned so far has been SmallBasic which doesn't support recursion very well (no local variables). I'm not against teaching another language, but still want to understand if there is a good way to solve this without recursion.
The problem is this: Given the sequence of numbers 1 2 3 4 5 6 7 8 9, insert +'s and -'s between numbers so that the result adds up to 101. For instance, 1+23+4+5+67-8+9=101.
The recursive solution looks something like this:
next(total, number, nextNumber, sequenceString)
{
//add
next(total + number, ...);
//subtract
next(total - number, ...);
//do nothing (multiply)
next(total, number * 10, ...);
}
Is there an iterative solution to this that isn't terribly complex?