Some years ago, at a nice dinner with some geeks after a programming contest, somebody presented to me the following problem: Given the numbers 1, 3, 4 and 6, find an expression that yields 24. The expression can use addition, subtraction, multiplication, division, parentheses as much as you want. You have to use all the numbers exactly once. Don’t concatenate them: 1, 3 is not 13… As an example, 4 * (6 — 1) + 3 would be a valid expression. The only bad thing about that one is that it’s result is only 23, one short of 24. Can you find a better one?
Brain training is at the moment very popular in my family, mostly due to a Pocket PC game called SPB Brain Evolution. So this should come as a welcome challenge, shouldn’t it? But programmer’s are lazy, people say. Instead of shuffling around numbers and operators for hours, why not write a program to do the task? (The fact that writing a program for this problem might take a couple of hours, too, is happily ignored ;-)) This I did, and as a bonus, it came up with a handful other nice problems. If you want to take your quest for the number 24 a bit further, why not use 1, 6, 7 and 9 to compute it? Or 2, 5, 7 and 8? What about 2, 7, 8, 9? In each case, there is exactly one way to reach 241.
But maybe 24 is too high a number and makes things overly complicated. Why don’t we try to obtain one instead? Using 1, 4, 6, 7 it should give you something to do during a boring lecture ;-)
Finally, you can download the sourcecode (in Python) if you’re interested in the solutions… or write a comment to this post to get a hint. Happy calculating!
1Note that 1+3=4 and 3+1=4 is counted as one solution, not two.
does (1^3)X4X6=24 count?
does (1^3)X4X6=24 count?
also does (5^2)-8+7=24
also does (5^2)-8+7=24 count?
I'm sorry, no...
I’m sorry, no… the idea to use powers is not too bad, but let me cite the task:
That means you’re restricted to +, -, * and /. Makes the task a bit more difficult, but also more interesting ;-)
haha, nice :) I only know
haha, nice :)
I only know the answer to the first set of number (1, 3, 4 and 6), but I won’t tell.
I’ll spend some time on trying to figure out the the solutions for the other sets (without the lazy programmer’s approach (well after a quick look at the source I’d say diligent programmer is more suitable)).
Re: haha, nice :)
Well congratulations for the first problem! And thanks for the praise… well maybe there would be a much easier way to solve it, and my code is just bloated up? But anyway, as long as one likes to program I think it’s fine ;-)
Apropos programming: anybody interested in teaming up for the International Contest in Functional Programming? The past years it was great fun, even for people who don’t know what functional means… It takes place from Friday evening to Monday evening (11th to 14th July) and there is no limit on team size, so join us for a crazy weekend!