My mom sent me this simple problem.Combine four fours arithmetically (i.e. 4 / 4 – 4 * 4) so the result is 20. The following solution is written in C++ and uses brute force to find all possible solutions:

/*
 *  combo.cxx - Four Fours Combination Problem Solver
 *              (using brute force)
 *
 *  Solves the simple problem: How do you combine four fours 
 *       using standard arithmetic operations to equal 20.
 *
 *  This program solves this puzzle using brute force and 
 *       shows the answer ignoring order of operations.
 *
 *
 *  Sumit Khanna / /tech/
 *    free to modify and redistribute
 */

#include <iostream>
using std::cout;
using std::endl;

int doOp(char op, int a,int b) {
  if(op == '+') {
    return a + b;
  }
  else if(op == '-') {
    return a - b;
  }
  else if(op == '*') {
    return a * b;
  }
  else if(op == '/') {
    return a / b;
  }
  else {
    cout << "Error. Invalid Operation " << op << endl;
    exit(2);
    return 0;
  }
}

int main(int argc, char **argv) {

 char *ops = new char[4];
 ops[0] =  '+';
 ops[1] =  '-';
 ops[2] =  '*';
 ops[3] =  '/';

 for(int i=0; i<4; i++) {
   for(int j=0; j<4; j++) {
     for(int k=0; k<4; k++) {

          int r = doOp(ops[i],4,4); 
          r = doOp(ops[j],r,4);
          r = doOp(ops[k],r,4);

          if(r == 20) {
            cout << " 4 " << ops[i] << " 4 " << ops[j] << " 4 " << ops[k] << " 4 = 20 " <<  endl;
          }

     }
   }
 }
 
 cout << "Note: Solutions ignores order of operations" << endl << endl; 

 delete[] ops;
 exit(0);

}

Comments

Eressenue 2008-12-19

The good resource should be brought in bookmarks

Comments are closed. Why?