Odd or Even integer?

Discussion in 'iOS Programming' started by thedollarhunter, Nov 9, 2011.

  1. thedollarhunter macrumors member

    Joined:
    May 9, 2011
    Location:
    UK
    #1
    Any ideas on the simplest way to test if an integer is odd or even?

    I want to be able to do something like this:

    Code:
    if(isEven(someVar)==1){
    //...
    }else{
    //...
    }
    There must be something built into C++ :confused: or do I need to have a little divide by 2 into float and check it kind of function?
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Don't need C++. Or even Objective-C. The plain old modulo operator in C is all you need (%).

    Code:
    if ((anInteger % 2) == 0 )
    {
      // Even
    }
    else
    {
     // Odd
    }
    
     
  3. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #3
    Use modulo 2.

    Code:
    if (num%2)
    {
    //The number is odd.
    }
    
    else
    {
    //The number is even.
    }
    Edit: Robbie beat me to it.

    Anyways, if you don't know what modulo is, it's just an operation that divides the first number by the second number and tells you what the remainder is. You use it by typing a percent sign, %. So if you take odd%2, the remainder will be 1, thus odd%2 is true, whereas if you take even%2, the remainder will be 0, thus even%2 is false.

    Here's the wikipedia page on modulo:
    http://en.wikipedia.org/wiki/Modulo_operator
     
  4. thedollarhunter thread starter macrumors member

    Joined:
    May 9, 2011
    Location:
    UK
    #4
    Perfect and thanks for the speedy posts.

    I found (random() % 6) really useful which I guess (with my feable understanding of math) is the same operation but used a different way?

     
  5. North Bronson macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #5
    Another trick that should work is to just check if the rightmost bit is set to zero or one.

    Code:
    if (integer & 1)
    {
        NSLog(@"ODD");
    }
    else
    {
        NSLog(@"EVEN");
    }
    though this might not always work if you are dealing with integers less than zero.
     
  6. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #6
    random() returns a random number, %6 would take the random number, divide it by 6, and tell you what the remainder is.

    if random() returns... then random()%6 is...
    0... 0
    1... 1
    2... 2
    3... 3
    4... 4
    5... 5
    6... 0
    7... 1
    8... 2
    9... 3
    10... 4
    11... 5
    12... 0
    13... 1

    and so on. Thus random()%6 returns a random integer between 0 and 5.
     
  7. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #7
    It does work even for negative numbers, at least using two's complement. :)
     

Share This Page