View previous topic :: View next topic |
Author |
Message |
rnielsen
Joined: 23 Sep 2003 Posts: 852 Location: Utah
|
Odd or even number |
Posted: Fri Jul 08, 2005 10:21 am |
|
|
This may be a dumb question but what's an easy way to determine if a number(variable) is odd or even?
Ronald |
|
|
Ttelmah Guest
|
Re: Odd or even number |
Posted: Fri Jul 08, 2005 10:25 am |
|
|
rnielsen wrote: | This may be a dumb question but what's an easy way to determine if a number(variable) is odd or even?
Ronald |
For an integer, it couldn't be easier!. Use a bitwise '&' with '1'. If this is non-zero (true), the number is odd.
So:
Code: |
#define isodd(x) ((x)&0x1L)
//Use this like:
if (isodd(value)) {
//Here the number was odd
}
|
Best Wishes |
|
|
sseidman
Joined: 14 Mar 2005 Posts: 159
|
Re: Odd or even number |
Posted: Fri Jul 08, 2005 10:26 am |
|
|
rnielsen wrote: | This may be a dumb question but what's an easy way to determine if a number(variable) is odd or even?
Ronald |
Assuming an integer, if the LSB is zero, the number is even.
Scott |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Jul 08, 2005 10:26 am |
|
|
You just test the LSB. |
|
|
kender
Joined: 09 Aug 2004 Posts: 768 Location: Silicon Valley
|
|
Posted: Fri Jul 08, 2005 10:51 am |
|
|
Code: |
if (n & 0x01)
{
// odd
}
else
{
// even
}
|
|
|
|
rnielsen
Joined: 23 Sep 2003 Posts: 852 Location: Utah
|
|
Posted: Fri Jul 08, 2005 11:06 am |
|
|
Thanks. I like the LSB bit test. Simple.
Ronald |
|
|
Ttelmah Guest
|
|
Posted: Fri Jul 08, 2005 3:21 pm |
|
|
I have to wonder if this thread was actually a 'record'. Four answers, all with basically the same solution in one minute!. I have seen a couple of overlapped answers before, but four is pretty amazing. :-)
Given that the writers, can't see other answers 'in preparation', it shows a remarkable activity level on the group.
Best Wishes |
|
|
treitmey
Joined: 23 Jan 2004 Posts: 1094 Location: Appleton,WI USA
|
|
Posted: Fri Jul 08, 2005 3:49 pm |
|
|
Great minds think alike. |
|
|
|