Using ADD, SUB, MULT and DIV to put specific values ​​in squares?

I had a developer interview today and had to do this aptitude test ... I got stuck on two questions:

box 1  box 2  box 3
 A      B      C

      

How do I put A in each box with only those 4 operators (ADD, SUB, MULT and DIV)?

box 1  box 2  box 3

      

You have numbers 1,2 and 3, which can be either box1 box2 or box3, but we don't know which one ... How to put 7 in box 3?

Can someone explain to me how to do this? ps: syntax: ADD, 1,2,3 => box3 = box1 + box2

thank

+3


source to share


1 answer


For the first question, you can set the B and C fields to 2A, simply by keeping A + A in each:

ADD 2, 1, 1
ADD 3, 1, 1

      

Now, just subtract A from each field:

SUB 2, 2, 1
SUB 3, 3, 1

      

This causes A to persist all over the place. Thus, the resulting program

ADD 2, 1, 1  // Box 1 = A  Box 2 = 2A  Box 3 = C
ADD 3, 1, 1  // Box 1 = A  Box 2 = 2A  Box 3 = 2A
SUB 2, 2, 1  // Box 1 = A  Box 2 = A   Box 3 = 2A
SUB 3, 3, 1  // Box 1 = A  Box 2 = A   Box 3 = A

      

On the second question, one cute trick would be to split the box by its own value in order to put a 1. For example:

DIV 1, 1, 1

      

Now put 2 in box 2 by doubling the contents of box 1 and saving it there:

ADD 2, 1, 1

      



Now put 4 in box 3 by doubling the contents of box 2 and saving it there:

ADD 3, 2, 2

      

Then add 2 to box three by adding to the contents of box 3. This makes box 3 hold 6:

ADD 3, 3, 2

      

Finally, add 1 to box three by adding content to box 3. This makes box 3 contain 7:

ADD 3, 3, 1

      

So the general program

DIV 1, 1, 1   // Box 1 = 1  Box 2 = ?  Box 3 = ?
ADD 2, 1, 1   // Box 1 = 1  Box 2 = 2  Box 3 = ?
ADD 3, 2, 2   // Box 1 = 1  Box 2 = 2  Box 3 = 4
ADD 3, 3, 2   // Box 1 = 1  Box 2 = 2  Box 3 = 6
ADD 3, 3, 1   // Box 1 = 1  Box 2 = 2  Box 3 = 7

      

Hope this helps!

+4


source







All Articles