Even/Odd help

Write an expression that evaluates to true if the integer variable x contains an even value , and false if it contains an odd value .

(!(x % 2))
Last edited on
Thank you!


Is there another way to write it?
!!((x-1) % 2)

There are many ways of writing it. Next time try googling or putting forth some effort of your own.
1
2
3
4
5
if(x % 2 ==0){
  return true;
}
return false;
Last edited on
Hengry wrote:
...

That is not an expression.
((X&2)&&!(X&1))
I think. something like that.
@jonnin
No, even for positive unsigned integers like 4, that doesn't work. Simply (!(x & 1)) is closer. Additionally, for negative values in (e.g., two's one's complement representation) this doesn't work for all x < 0.
Last edited on
Hello esokoletsky,

This is simple and has worked for all the positive and negative numbers I have tried so far.

1
2
3
4
5
6
	x % 2 ? result = false : result = true;

	if (result)
		std::cout << "\n Number is even" << std::endl;
	else
		std::cout << "\n Number is odd" << std::endl;


Adjust the type of "x" for the size of the number you need.

Hope that helps,

Andy
Write an expression that evaluates to true ...
1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    int x = 32;
    std::cout << std::boolalpha << (x % 2 == 0);
}
Last edited on
Just re-reading the OP:
Write an expression that evaluates to true if the integer variable x contains an even value, and false if it contains an odd value .

One interpretation of this could be that 769 would evaluate to true since it contains 6 (an even value) and the same number would also evalute to false since it contains 7 and 9 and hence the problem is ill-defined???
Or, more specifically, what does 'containing a value' mean for an integer type?
Last edited on
I was way off (trying to think when tired, and failed) ... but it does work on signed values if you do it right.

the trick is to look at the least bit, which if 1, is odd.

try 4, for example, that is binary 100 and that works.

now try -4... the 2's comp is flip bits and +1:
more precisely, 4 in a byte is 00000100
and -4 in a byte is then 11111100 ... still works (flip all bits, add 1)

because its the least bit, and that is always 0 for an even value, and you flip it, so its always 1, then add 1, its always 0 again, ... so it will work on negatives just fine.

so the right way would have been simply
!(x&1)

I think this has come up recently. (@JLBorges had to correct me on grounds of portability).

http://www.cplusplus.com/forum/beginner/207434/#msg979132
@jonnin, sure enough it works in twos complement, but not in one's complement.
(My idea was correct, but my example wasn't.)

I need to be more careful. I seem to be posting misinformation much too often lately....
My apologies :(

Hah, this after my epic doh post above, where I mangled it beyond recognition?
Stuff happens, no need to apologize :)

Topic archived. No new replies allowed.