I would like to use Mathematica to create a simple program in which we can find all ways to construct 21 by using each of 1, 5, 6, and 7 exactly once. The numbers may be combined in any way using any of the primary binary operators, i.e. addition, subtraction, multiplication, and division, as well as parenthesis. I feel that the method of brute-forcing all possible combinations of 1, 5, 6 and 7 would likely be effective, but I am having trouble structuring the code. My approach would likely be the following:

  1. Define a vector S = (1, 5, 6, 7)
  2. Remove any two numbers in S and perform an arbitrary binary operation on the two numbers, obtaining a new number a.
  3. Replace a into S, generating S'.
  4. Repeat from step 1 until this particular brute-force branch generates a final value.

Hence, the cycle would repeat until S reduces to one element. If the branch results in 21, we would be done. The problem is I do not know how to code steps 2 and 3 in Mathematica, and would like some help on how to structure my code, or if my approach isn't efficient, on changing up my approach.

  • 1
    $\begingroup$ possible duplicate: mathematica.stackexchange.com/questions/15021/… $\endgroup$ – happy fish Mar 18 '17 at 7:17
  • $\begingroup$ user47442, I am inclined to close this question as a duplicate of the one happy fish proposed above. Do you agree? If not what is your case for differentiating it? $\endgroup$ – Mr.Wizard Mar 23 '17 at 4:54

Maybe this can help...There is the new in 11 Groupings command but it only gets one answer?!

ans = Groupings[Permutations[{1, 5, 6, 7}], {Plus, Subtract, Times, Divide} -> 2, HoldForm]
Quiet[Select[ans, ReleaseHold[#] == 21 &]]


The first line is straight from the docs, can the second line be improved? Are there more solutions?

  • 3
    $\begingroup$ thanks for introducing me to Groupings`+1:) $\endgroup$ – ubpdqn Mar 18 '17 at 8:58
  • $\begingroup$ @ubpdqn, you are very welcome. $\endgroup$ – bobbym Mar 18 '17 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.