Over the weekend I wrote a little ugly perl in order to solve the ‘four fours‘ problem.

Essentially the problem is to make as many positive integers as you can, using only four occurrences of the digit ’4′, and some mathematical symbols. For instance:

17 = ( 4  * 4 )  + ( 4  / 4 )

There are several different variants of the rules to this game, mostly concerning what types of symbol you are allowed. I let you control these with command line switches, and support:

• Decimals (e.g. .4)
• Recurring decimals (e.g. .4~)
• Square roots
• Power (e.g. 4 ** 4)
• Factorial (e.g. 4!)
• Multidigit numbers (or decimals), e.g. 44, 4.4

You can also specify a different number of fours or a different digit.

With the ‘christmas tree’ option turned on (i.e. use everything), it cannot find 17 integers between 1 and 200 (113, 141, 147, 157, 163, 166, 167, 171, 173, 177, 183, 185, 187, 191, 193, 197 and 199). My solution to 123 = ( 44 / .4~ ) + 4! is simpler than Wheeler’s sqrt(sqrt(sqrt((sqrt(4)/.4)^4!)))-sqrt(4), though you it will find that too if you switch off recurring decimals.

You can find the source code here. I do not claim that it is optimised or beautiful. In particular, the treatment of rounding is fairly disgusting. If only I could ‘use Surds;‘.