I just realized this

Not sure why it took me this long, but... yeah...

1
2
3
4
5
6
7
8
9
10
11
//Return 1 on true and 0 on false
bool isEven(int _x)
{
	return !(_x & 1);
}

//Return 1 on true and 0 on false
bool isOdd(int _x)
{
	return (_x & 1);
}
Most people use modulus by 2, but your solution works too. Also, why have two functions? Obviously if it's !isEven() then it's odd.
Last edited on
Lol, because I do not think things through :P
1
2
3
4
5
template<typename T>
bool isEven(T t)
{
    return t%2 == 0;
}
If you want to get fancy you can use std::enable_if to make sure it only works for primitive and/or integral types.
How is modulus implemented in C/C++ ?

the template seems useless though because mod only works with integer types
The template will work for all integral types and any class types that overload operator%. Your functions only work for int and below (no support for unsigned or long long types or custom types).

I'm not sure what you mean by "How is modulus implemented in C/C++ ?", could you not just test?

Also I think your code and my code would both be optimized to the same code by the compiler, it's just that yours is more obfuscated.
Last edited on
it's just that yours is more obfuscated.

I don't think either method is obfuscated, especially given the function name(s.)
For any reasonable numeric value of x in Z both (x & 1) and (x % 2) result in the same value. Otherwise overload T cannot claim to be numeric.

[edit] Compilers should optimize the same for both, but the first is a well-known idiom because the second is not so nice for not-so-smart (older) compilers.
Last edited on
What about (x % 2_Number) where there exists an operator% with a left hand type of float/double/long double and a right-hand type of whatever 2_Number is? You can't do bitwise operations on floating point types.

And once again LB finds an insane way to prove a statement wrong.
Last edited on
x in Z

Agreed about the difficulty with floats; just saying that checking even/odd is an integer operation.
Ah, OK. That makes sense.
> For any reasonable numeric value of x in Z both (x & 1) and (x % 2) result in the same value.
¿isn't the sign implementation defined if x<0?
@ne555: In that case just force it positive with (x % 2) & 1 (wait...?)
Hmm, I should have said Z+, I guess.

Whatever. I concede the point. :-J
Topic archived. No new replies allowed.