Encoding 2 numbers into 1

3.2k Views Asked by At

Say we have two integers, $a$ and $b$. I need a way to combine these numbers into one unique number $x$, such that they can both be recovered from $x$ and no other numbers can be recovered from $x$ There are plenty of ways to do this, but the problem is that I am using this for programming and I only have the following operators:

$+$ $-$ $\times$ $\div$ $a^x$ $\sqrt{}$

I also have sin and cos but I doubt those will be needed. Is it possible to encode and decode $a$ and $b$ using just these operators?

2

There are 2 best solutions below

2
On

Try $x=2^a (2b+1)$.

This relies on every integer being written uniquely as a power of $2$ times an odd number.

It is easy to recover $a$ and $b$: just divide $x$ by $2$ until you reach an odd number. Then $a$ is the number of divisions and $b$ is easily extracted from what is left.

However, if you need this for programming, then $a$ will be constrained to be quite small, if you use native numbers. In this context, the problem cannot be solved in full generality because you cannot compress all $2n$-bit strings into $n$-bit strings injectively.

1
On

You didn't specify whether $x$ needed to be an integer. In order to avoid massive numbers in exponentation, we could take $$x=a+\frac{1}{b}$$ Since $a,b$ are integers, $a$ will just be the integer part of $x$ and $1/b$ will be the reciprocal part, which you should be able to computationally reciprocate and round to the nearest integer (again, if $b$ is too big this may lead to floating point errors but this should be much better than calculating $2^a$ or similar).