SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: even numbers...

Hybrid View

  1. #1
    SitePoint Enthusiast ErikN's Avatar
    Join Date
    Jul 2001
    Posts
    84
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    even numbers...

    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...

  2. #2
    SitePoint Enthusiast
    Join Date
    May 2001
    Location
    lalal
    Posts
    85
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    maybe something like

    PHP Code:
    function is_even($num)
    {
        return (
    $num&1)?0:1;


  3. #3
    JavaScript Guru (Big Ego) Arielladog's Avatar
    Join Date
    Jul 1999
    Location
    SC, USA
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  4. #4
    Making a better wheel silver trophy DR_LaRRY_PEpPeR's Avatar
    Join Date
    Jul 2001
    Location
    Missouri
    Posts
    3,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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 ** Ignore old signature for now... **
    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

  5. #5
    SitePoint Enthusiast ErikN's Avatar
    Join Date
    Jul 2001
    Posts
    84
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I used DR_LaRRY_PEpPeR's because it's shorter and it works...but thanks everybody for helping


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •