5

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 ?

homegrown
  • 3,678

2 Answers2

13

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}.$$

Unit
  • 7,601
  • 2
    +1 Of course, given any $f(x)$ satisfying this, $g(x)=1-f(x)$ is good for $g$. :) – Thomas Andrews Dec 20 '14 at 22:10
  • 1
    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 '14 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.... – Thomas Andrews Dec 20 '14 at 22:28
1

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)
mvw
  • 34,562
  • 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. – Thomas Andrews Dec 20 '14 at 22:35
  • I would recommend a test, if one needs to adjust the sign, see this table about the behaviour for negative arguments: http://en.wikipedia.org/wiki/Modulo_operation – mvw Dec 20 '14 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. – Thomas Andrews Dec 20 '14 at 22:43
  • Thanks for pointing out that problematic. The question is still fuzzy. – mvw Dec 20 '14 at 22:53