Is there a way to tell whether a number is even or odd? I'd like to set something up where if the number is even, it does something, and if the numbers odd, then it does something else...
| SitePoint Sponsor |
Is there a way to tell whether a number is even or odd? I'd like to set something up where if the number is even, it does something, and if the numbers odd, then it does something else...
maybe something like
PHP Code:function is_even($num)
{
return ($num&1)?0:1;
}


Hey guys,
There are MANY ways to do this, but there is an operator that in my opinion was meant to handle this kind of stuff. The modulus operator (%) returns the remainder after division:
2%2 == 0
5%3 == 2
25%6 == 1
Etc... So, an even number is divisible by 2 without a remainder. So, if n is out number, we can say:
if(n%2==0){
// number is even
}else if(n%2==1){
// number is odd
}
Hope that helps,
aDog![]()
Moderator at www.javascriptcity.com/forums/
i prefer the bitwise and operator myself.as you get into bigger numbers it's a little faster than modulus. just and a number by 1 to see if it's even.
PHP Code:if ($num & 1) { /* it's even*/ }
- Matt
Dr.BB - Highly optimized to be 2-3x faster than the "Big 3."
"Do not enclose numeric values in quotes -- that is very non-standard and will only work on MySQL." - MattR
I used DR_LaRRY_PEpPeR's because it's shorter and it works...but thanks everybody for helping![]()
Bookmarks