How to Solve it by Computer #2

Problem 2.1.4: Given two variables of integer type a and b, exchange their values without using a third temporary variable

I read about a nifty trick doing this a few years ago but I don’t remember it. So let’s try to figure it out. It’s quite clear that we have to do something to both variables so that we can calculate the one from the other. So, the first step is something like that:

A simple idea would be to shift the bits which only works if we have enough space. An example would be if we have A = 1011 and B = 1111 in this case we could create shift B by 4 to create A = B = 1111 1011. And then take the first 4 bits for A and the last 4 bits for B.

Let’s think about a solution using the decimal system. Taking an example is easier: A = 12 and B = 4; I wanted to avoid using two prime numbers which would make that easier. Let’s try multiplication:

Another example:

I’m surprised but it works. Cool :)

This site uses Akismet to reduce spam. Learn how your comment data is processed.