# Best function getting 0 for odd parameter, 1 for even

I'm looking for two functions, assuming x is an integer: $$f(x) = \begin{cases}0&\text{if x is odd}\\1&\text{if x is even}\end{cases}$$ and $$g(x) = \begin{cases}1&\text{if x is odd}\\ 0&\text{if x is even}\end{cases}$$

For now I went up with the following : $$f(x) = \frac{\cos(x\pi)+1}{2}$$ and $$g(x) = -\frac{\cos(x\pi)-1}{2}$$

Is there any better / faster way ?

• You mean you wanted continuous functions with this property? Because what you defined in the first line were fine function definitions. Dec 20, 2014 at 22:06
• What about just using the mod function: $g(x)=mod(x,2)$ Dec 20, 2014 at 22:08
• This should evaluate pretty fast: min(abs x', abs(x'-2)) where x' = x mod 2 Dec 20, 2014 at 22:10
• In C or most C-like languages, g(x)=abs(x)%2 is good enough. For $f(x)$, use 1-g(x) or even !g(x) Dec 20, 2014 at 22:13
• What does fast mean in your question - you are talking about some implementation in a computer language?
– mvw
Dec 20, 2014 at 22:21

Since parity isn't defined on $\mathbb{R}$, I assume you want $x$ to be an integer $n$, in which case your functions simplify to $$f(n) = \frac{1 + (-1)^n}{2}$$ and $$g(n) = -\frac{(-1)^n - 1}{2} = \frac{1 + (-1)^{n+1}}{2}.$$

• +1 Of course, given any $f(x)$ satisfying this, $g(x)=1-f(x)$ is good for $g$. :) Dec 20, 2014 at 22:10
• In this case, $1-f(n) = 1-\frac{1}{2}(1+(-1)^n)=\frac{1}{2}(2-1-(-1)^n)=\frac{1}{2}(1-(-1)^n)=\frac{1}{2}(1+(-1)^{n+1})$ is $g(n)$.
– Unit
Dec 20, 2014 at 22:13
• Yeah, was just noting that it works in general, whatever $f(x)$ is. Although I don't see how this $f(n)$ is particularly "fast." Certainly, faster than computing cosine. But OPs original question is odd, since the definitions at the top are essentially the most efficient ways to implement the functions.... Dec 20, 2014 at 22:28

Use the remainder function for division by two or test for the lowest bit. Fast depends on your language.

\begin{align} g(x) &= x - 2 \lfloor x / 2 \rfloor \\ f(x) &= 1 - g(x) \end{align}

In C like languages:

odd = x % 2   // use abs(x) for negative x if
// your lang uses the dividend's sign


or

odd = x & 1:


the logical negative case:

even = (x % 2 == 0)
even = (x & 1 == 0)

• Technically, x%2 returns negative values when x is negative, so your first odd is wrong. (I really hate that about C's %.) And no, I didn't downvote. Someone randomly downvoted my answer, too. Dec 20, 2014 at 22:35
• I would recommend a test, if one needs to adjust the sign, see this table about the behaviour for negative arguments: en.wikipedia.org/wiki/Modulo_operation
– mvw
Dec 20, 2014 at 22:41
• I tested it already myself, with a program that computed (-11)%2, GCC on a MacOS X. But I used to test C compilers for a living, so I was pretty sure of the result. Dec 20, 2014 at 22:43
• Thanks for pointing out that problematic. The question is still fuzzy.
– mvw
Dec 20, 2014 at 22:53