# Simple Challenge

• 02-11-2011
Simple Challenge
Complete the function IsEven() with just 1 line of code and without using Mod (%), +,*,-, or any built in functions.

NB. A line of code ends with a ';'

Good luck =D

Code:

```#include <iostream> using namespace std; bool isEven(int f) {     //code here } int main (int argc, char * argv[]) {     int f;     cout << "Enter # ";     cin >> f;     cout << f << ( isEven(f)  ?  " is even" : " is odd" ) << endl;     return 0; }```
• 02-11-2011
whiteflags
Even if you know the trick, it isn't guaranteed to work like mod... Mod works no matter what your system does to represent negative numbers.
• 02-11-2011
Quote:

Originally Posted by whiteflags
Even if you know the trick, it isn't guaranteed to work like mod... Mod works no matter what your system does to represent negative numbers.

that's true. at least you know the 'trick'.
• 02-11-2011
Elkvis
I can think of 3 ways to do this:

binary & operator
left/right shifting
division/multiplication
• 02-11-2011
whiteflags
Using bit shifting amounts to multiplication or division, but that should indeed work.
• 02-11-2011
oh whiteflags it wasn't intended to work like mod. every even number's last bit is 0 and odd's are 1. so by ANDing the last bit you can figure out which of the two it is. it doesn't find the remainder if that's what u thought.
• 02-11-2011
phantomotap
O_o

That's clearly not what he thought.

He was saying that the "trick" may not work if your system doesn't use "Two's Complement" representation for negative numbers whereas using `mod' will.

Soma
• 02-12-2011
GReaper
Code:

```bool IsEven(int f) {     return !(((f < 0) ? -f : f) & 1); }```
That trick solves the negative-number-representation problem.

:cool:

EDIT: Unless the representation is 1s Complement and f == -0 ( Yes, in 1s Complement 0 and -0 are different )
EDIT^2: Anyway, what CPU uses 1s Compement nowadays?
• 02-13-2011
bobknows
couldnt u just make another function to do it with several lines and put it in as
Code:

```bool iseven(int f) {       return eventest(f); }```
where eventest returns if it is even or not?
• 02-13-2011
nimitzhunter
Quote:

Originally Posted by bobknows
couldnt u just make another function to do it with several lines and put it in as
Code:

```bool iseven(int f) {       return eventest(f); }```
where eventest returns if it is even or not?

that is just bending the rule to the breaking point.
• 02-14-2011
bobknows
yep :P also another way, use all the lines you want, just dont hit enter

Code:

`/* some code */; /* some more code*/; /*even more code*/;`