Determining parity of a number

204 Views Asked by At

I have this function:

$$f(n) = \frac{(-1)^n + 1}{2}$$

For $n \in Z$ It seems be equal to $1$ if $n$ is an even number and $0$ otherwise:

$$ \begin{array}{c|c} n & -3 & -2 & -1 & 0 & 1 & 2 & 3 \\ \hline f(n) & 0 & 1 & 0 & 1 & 0 & 1 & 0 \end{array} $$

It seems to me that it is the same as:

$$1-(n \mod 2)$$

Is there some other representation of this function which does not use $(-1)^n$? I would like to stay as close as possible to basic algebraic operations like addition, subtraction, multiplication, division or exponentiation and to avoid modulo, floor, ceiling and similar.

4

There are 4 best solutions below

1
On BEST ANSWER

I don't know of an easier form of your function, its already in simplest terms. What about this function?

$\displaystyle\frac{1}{2}(\frac{(-n)^n}{n^n}+1)$

It has the exact properties you mention, addition, subtraction, division, multiplication and exponentiation.

There is also an integral,

$\displaystyle\frac{n}{2}\int_{-1}^{1}x^{n-1} dx=\frac{1-(-1)^{n}}{2}.$

How about

$gcd(n,2)-1$

And, although you don't want floor function,

$\displaystyle\lfloor\frac{n}{2}\rfloor-\lfloor\frac{n-1}{2}\rfloor=\frac{1+(-1)^n}{2}.$

If none of these work, what's wrong with simply 1 if even and 0 if odd?

As a side note, $(-1)^{n}$ literally means just multiply $-1$ by itself n times.

3
On

Most languages that contain arithmetic also contain integer arithmetic. Sometimes they will do it by having a concept of an integer data type. Sometimes they will do it by having an explicit integer division operator (such as \ in some versions of Basic). Sometimes they will do it by having a "round down to the nearest integer" function called floor() or Int().

Let me write this "integer division" operator as ÷. Then $n\pmod 2$ can be found with n-(n÷2)*2, and your function can be found with 1 minus that: 1-(n-(n÷2)*2).

There is the prospect of an anomaly depending on whether integer division of negative numbers is mathematically correct. Many languages make $(-1)÷2$ not -1 but 0, so that your function applied to -2 would generate -1 and not 1. If you have abs() in your repertoire then you could use it to turn -1 into 1. Alternatively, if you knew that $n$ was never less than (say) 1000, you could just add 1000 to it before applying the function.

1
On

Mathematicians do use shortcuts to make their life easier and everyone else's life easier. ⎣floor⎦, ⎡ceil⎤, |absolute value|, modulo operator, $1|_{condition}$ which is 1 when the condition is true and 0 otherwise. There is no reason not to use these.

0
On

$${1+\cos\pi n\over2}$$ does what you want. Or $\cos^2(\pi n/2)$, which is the same thing.