How can I check if a given number is even or odd in C?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
The bitwise method depends on the inner representation of the integer. Modulo will work anywhere there is a modulo operator. For example, some systems actually use the low level bits for tagging (like dynamic languages), so the raw x & 1 won't actually work in that case.
Use bit arithmetic:
This is faster than using division or modulus.
I would build a table of the parities (0 if even 1 if odd) of the integers (so one could do a lookup :D), but gcc won't let me make arrays of such sizes:
So let's instead resort to the mathematical definition of even and odd instead.
An integer n is even if there exists an integer k such that n = 2k.
An integer n is odd if there exists an integer k such that n = 2k + 1.
Here's the code for it:
Let C-integers denote the possible values of
int
in a given C compilation. (Note that C-integers is a subset of the integers.)Now one might worry that for a given n in C-integers that the corresponding integer k might not exist within C-integers. But with a little proof it is can be shown that for all integers n, |n| <= |2n| (*), where |n| is "n if n is positive and -n otherwise". In other words, for all n in integers at least one of the following holds (exactly either cases (1 and 2) or cases (3 and 4) in fact but I won't prove it here):
Case 1: n <= 2n.
Case 2: -n <= -2n.
Case 3: -n <= 2n.
Case 4: n <= -2n.
Now take 2k = n. (Such a k does exist if n is even, but I won't prove it here. If n is not even then the loop in
even
fails to return early anyway, so it doesn't matter.) But this implies k < n if n not 0 by (*) and the fact (again not proven here) that for all m, z in integers 2m = z implies z not equal to m given m is not 0. In the case n is 0, 2*0 = 0 so 0 is even we are done (if n = 0 then 0 is in C-integers because n is in C-integer in the functioneven
, hence k = 0 is in C-integers). Thus such a k in C-integers exists for n in C-integers if n is even.A similar argument shows that if n is odd, there exists a k in C-integers such that n = 2k + 1.
Hence the functions
even
andodd
presented here will work properly for all C-integers.done.
I'd say just divide it by 2 and if there is a 0 remainder, it's even, otherwise it's odd.
Using the modulus (%) makes this easy.
eg. 4 % 2 = 0 therefore 4 is even 5 % 2 = 1 therefore 5 is odd