Find an expression that equals 24 using the digits 1, 4, 5, and 6.
- Each digit must be used exactly once.
- You must use only addition, subtraction, multiplication, and division.
- Digits may not be concatenated (one may not put 1 and 4 together to make 14).
- Parentheses (brackets) are allowed.
____________________________
Find at least two solutions!
Two of the solutions posted were also found by computer program. They are listed here in RPN (Reverse Polish Notation), which avoids the need for parentheses. In this case as only 1-digit numbers are involved, no commas are needed to separate the numbers:
4156/-/
4156/-/
654/1-/
654/1-/
(each solution was found twice due to the algorithm used)
Explaining the RPN:
In the first solution above, the first / divides the 6 into the 5. Then the - subtracts that result from the 1. The final / divides that into the initial 4, so it's the equivalent of 4/(1-5/6).
In the same way the last solution is 6/(5/4-1).
The program:
DECLARE SUB permute (a$)
DEFDBL A-Z
source$ = "1456abc"
ops$ = "+-*/"
FOR perm = 1 TO 5040
FOR a = 1 TO 4
op(1) = a
FOR b = a TO 4
op(2) = b
FOR c = b TO 4
op(3) = c
stSize = 0
FOR i = 1 TO LEN(source$)
ch$ = MID$(source$, i, 1)
oper = INSTR("abc", ch$)
IF oper THEN
IF stSize < 2 THEN GOTO nextPerm
SELECT CASE op(oper)
CASE 1
stack(stSize - 1) = stack(stSize - 1) + stack(stSize)
CASE 2
stack(stSize - 1) = stack(stSize - 1) - stack(stSize)
CASE 3
stack(stSize - 1) = stack(stSize - 1) * stack(stSize)
CASE 4
IF stack(stSize) = 0 THEN GOTO nextC
stack(stSize - 1) = stack(stSize - 1) / stack(stSize)
END SELECT
stSize = stSize - 1
ELSE
stSize = stSize + 1
stack(stSize) = VAL(ch$)
END IF
NEXT i
IF stSize <> 1 THEN GOTO nextPerm
IF ABS(stack(1) - 24) < .0000001 THEN
FOR i = 1 TO LEN(source$)
ch$ = MID$(source$, i, 1)
oper = INSTR("abc", ch$)
IF oper THEN
PRINT MID$(ops$, op(oper), 1);
ELSE
PRINT MID$(source$, i, 1);
END IF
NEXT
PRINT
END IF
nextC:
NEXT c
NEXT b
NEXT a
nextPerm:
permute source$
NEXT
The permute subroutine is left out as it appears elsewhere on the site.
Edited on June 9, 2004, 9:50 am
|
Posted by Charlie
on 2004-06-09 09:49:16 |