From a mathematical point of view, describing such a function is trivial: $ f(x)=\begin{cases} 0 & \text{if } x \in \{1,4\} \\ 1 & \text{if } x \in \{2,3\} \\ \end{cases}.$ It's not a particularly slick formula for the function, but it's certainly straightforward. An alternative is to search for "magic numbers". For example: $f(x)=2x^2+3 \mod 5.$ To find this function, I just let my computer search until the numbers happened to match.
If you're looking for an efficient implementation of this function, in C say, any one of these would compute the function:
char f=(x&2)>>1; char f=(x>>1)%2; // this is Ross Millikan's suggestion char f=(x>>1)&1;
Here &
is bitwise and
, >>
is right bit-shift by one, and %
is the mod operation.
If you only need an if(f!=0) { ... }
statement (i.e., "if $f(x)\neq 0$"), then this would suffice:
if(x&2) { ... }
An alternative to the above is simply storing the values in memory. E.g. via:
char f[5]={0,0,1,1,0};
whenceforth, if you want to compute $f(x)$, you can just recall f[x]
from memory.