Automatic searches for solutions to a recreational problem

56 Views Asked by At

I would like to examine the relationship of 5 numbers. 3,38,5,x set equal to .8 using abstract algebra. Yes I know (5/(38+3))*8 and (3/(38+5))*11 are close but I'm doing this all the time and I'd like to automate it with something proven to be correct. Is it possible to use wolfram alpha or some other webpage to give me possible order and operators to solve this equation? I know I could use a genetic algorithm but I would rather not waste time and cpu power writing one for something so simple.

1

There are 1 best solutions below

0
On

This is not really a math question, but a programming exercise. In python, your problem looks like:

import itertools as itr
import operator as op

operations = [op.add, op.sub, op.mul, op.truediv]
known_vals   = [3,38,5]
target       = .8
epsilon      = 10**(-8)

for z in xrange(1, 1000):
    vals = known_vals + [z,]
    for OP in itr.product(operations, repeat=len(vals)-1):
        for seq in itr.permutations(vals):
            op = iter(OP)
            result = reduce(lambda *x: next(op)(*x), seq)
            if abs(result - target) < epsilon:
                print OP, seq, result

This is a simple brute force search that does not take into account associativity or commutativity of the input operations. Nevertheless, if you are looking for simple solutions this might get you started. On your input a "perfect" match comes in at:

(<built-in function truediv>, <built-in function truediv>, <built-in function truediv>) (456, 5, 3, 38) 456 0.8

Which is equivalent to

$$ ((456/5)/3)/38) = 0.8 $$

Note that $5 * 3 * 38 = (4/5)*456$ as other commenters have noted. Another solution (of many) is $(38-26)/3/5$. If you want other "close" solutions, progressively raise the value of epsilon.