It is odd that I woke up thinking about this and all the different ways I have implemented this test as my programming skill and understanding improved, so here's a whistle stop tour. I think its interesting to see the way thought processes change...
Ok, so when I was 15, my good friend Tim was pondering the same question, my answer was to use a float and an int.
Say that we want to test if '5' is even.
int a = 5;
float b = 5;
a = a / 2;
b = b / 2;
if(b!=a) // If they are not equivalent then the number is ODD!
As you can see, this is rather in efficient but at the time, it worked.
A little while later we learned about the % operator, so we can do something like this:
int a = 5;
int b = 5 % 2;
if(b>0) // If b is > 0 then the number is ODD!
Then I went to cern, worked for a while on some pretty high performance C and ended up writing this without thinking about it:
#define isEven(x) x&0x1
Learning is fun :-P
No comments:
Post a Comment