How do I check if an integer is even or odd? [clos

2019-01-02 14:24发布

How can I check if a given number is even or odd in C?

标签: c integer
30条回答
爱死公子算了
2楼-- · 2019-01-02 14:47

As some people have posted, there are numerous ways to do this. According to this website, the fastest way is the modulus operator:

if (x % 2 == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

However, here is some other code that was bench marked by the author which ran slower than the common modulus operation above:

if ((x & 1) == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

System.Math.DivRem((long)x, (long)2, out outvalue);
        if ( outvalue == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

if (((x / 2) * 2) == x)
               total += 1; //even number
        else
               total -= 1; //odd number

if (((x >> 1) << 1) == x)
               total += 1; //even number
        else
               total -= 1; //odd number

        while (index > 1)
               index -= 2;
        if (index == 0)
               total += 1; //even number
        else
               total -= 1; //odd number

tempstr = x.ToString();
        index = tempstr.Length - 1;
        //this assumes base 10
        if (tempstr[index] == '0' || tempstr[index] == '2' || tempstr[index] == '4' || tempstr[index] == '6' || tempstr[index] == '8')
               total += 1; //even number
        else
               total -= 1; //odd number

How many people even knew of the Math.System.DivRem method or why would they use it??

查看更多
余生无你
3楼-- · 2019-01-02 14:47

To give more elaboration on the bitwise operator method for those of us who didn't do much boolean algebra during our studies, here is an explanation. Probably not of much use to the OP, but I felt like making it clear why NUMBER & 1 works.

Please note like as someone answered above, the way negative numbers are represented can stop this method working. In fact it can even break the modulo operator method too since each language can differ in how it deals with negative operands.

However if you know that NUMBER will always be positive, this works well.

As Tooony above made the point that only the last digit in binary (and denary) is important.

A boolean logic AND gate dictates that both inputs have to be a 1 (or high voltage) for 1 to be returned.

1 & 0 = 0.

0 & 1 = 0.

0 & 0 = 0.

1 & 1 = 1.

If you represent any number as binary (I have used an 8 bit representation here), odd numbers have 1 at the end, even numbers have 0.

For example:

1 = 00000001

2 = 00000010

3 = 00000011

4 = 00000100

If you take any number and use bitwise AND (& in java) it by 1 it will either return 00000001, = 1 meaning the number is odd. Or 00000000 = 0, meaning the number is even.

E.g

Is odd?

1 & 1 =

00000001 &

00000001 =

00000001 <— Odd

2 & 1 =

00000010 &

00000001 =

00000000 <— Even

54 & 1 =

00000001 &

00110110 =

00000000 <— Even

This is why this works:

if(number & 1){

   //Number is odd

} else {

   //Number is even
}

Sorry if this is redundant.

查看更多
牵手、夕阳
4楼-- · 2019-01-02 14:48

You guys are waaaaaaaay too efficient. What you really want is:

public boolean isOdd(int num) {
  int i = 0;
  boolean odd = false;

  while (i != num) {
    odd = !odd;
    i = i + 1;
  }

  return odd;
}

Repeat for isEven.

Of course, that doesn't work for negative numbers. But with brilliance comes sacrifice...

查看更多
永恒的永恒
5楼-- · 2019-01-02 14:49

Number Zero parity | zero http://tinyurl.com/oexhr3k

Python code sequence.

# defining function for number parity check
def parity(number):
    """Parity check function"""
    # if number is 0 (zero) return 'Zero neither ODD nor EVEN',
    # otherwise number&1, checking last bit, if 0, then EVEN, 
    # if 1, then ODD.
    return (number == 0 and 'Zero neither ODD nor EVEN') \
            or (number&1 and 'ODD' or 'EVEN')

# cycle trough numbers from 0 to 13 
for number in range(0, 14):
    print "{0:>4} : {0:08b} : {1:}".format(number, parity(number))

Output:

   0 : 00000000 : Zero neither ODD nor EVEN
   1 : 00000001 : ODD
   2 : 00000010 : EVEN
   3 : 00000011 : ODD
   4 : 00000100 : EVEN
   5 : 00000101 : ODD
   6 : 00000110 : EVEN
   7 : 00000111 : ODD
   8 : 00001000 : EVEN
   9 : 00001001 : ODD
  10 : 00001010 : EVEN
  11 : 00001011 : ODD
  12 : 00001100 : EVEN
  13 : 00001101 : ODD
查看更多
浮光初槿花落
6楼-- · 2019-01-02 14:50

Try this: return (((a>>1)<<1) == a)

Example:

a     =  10101011
-----------------
a>>1 --> 01010101
a<<1 --> 10101010

b     =  10011100
-----------------
b>>1 --> 01001110
b<<1 --> 10011100
查看更多
皆成旧梦
7楼-- · 2019-01-02 14:51

Reading this rather entertaining discussion, I remembered that I had a real-world, time-sensitive function that tested for odd and even numbers inside the main loop. It's an integer power function, posted elsewhere on StackOverflow, as follows. The benchmarks were quite surprising. At least in this real-world function, modulo is slower, and significantly so. The winner, by a wide margin, requiring 67% of modulo's time, is an or ( | ) approach, and is nowhere to be found elsewhere on this page.

static dbl  IntPow(dbl st0, int x)  {
    UINT OrMask = UINT_MAX -1;
    dbl  st1=1.0;
    if(0==x) return (dbl)1.0;

    while(1 != x)   {
        if (UINT_MAX == (x|OrMask)) {     //  if LSB is 1...    
        //if(x & 1) {
        //if(x % 2) {
            st1 *= st0;
        }    
        x = x >> 1;  // shift x right 1 bit...  
        st0 *= st0;
    }
    return st1 * st0;
}

For 300 million loops, the benchmark timings are as follows.

3.962 the | and mask approach

4.851 the & approach

5.850 the % approach

For people who think theory, or an assembly language listing, settles arguments like these, this should be a cautionary tale. There are more things in heaven and earth, Horatio, than are dreamt of in your philosophy.

查看更多
登录 后发表回答