Hi all,

I'm new over here n want some help. What will be the solution, if we want to find out even/odd number without using divsion or modulus operator?

Best Regards.

Printable View

- 03-13-2006orangesEven/Odd Number without % or /
Hi all,

I'm new over here n want some help. What will be the solution, if we want to find out even/odd number without using divsion or modulus operator?

Best Regards. - 03-13-2006Thantos
Use subtraction

- 03-13-2006anonytmouse
Consider the binary layout of an integer and look up the bitwise & (and) operator.

- 03-13-20067stud
You can read the number into a string stream, and then using a switch() statement if myStr[myStr.length() - 1] is equal to '1', '3', '5', '7', or '9', then the number is odd. If the number's not odd, then it's even.

- 03-13-2006Rashakil Fol
Sure, but don't you think that uses the % operator?

Use two mutually recursive functions! - 03-14-20067studQuote:

Sure, but don't you think that uses the % operator?

*know*that it does not. - 03-14-2006iMalcQuote:

Originally Posted by**anonytmouse**

Code:`if (x & 1)`

{

cout << "OMFG x is ODD!!!" << endl;

}

else

{

cout << "OMFG x is EVEN!!!" << endl;

}

- 03-14-2006grumpy
Not quite as efficient as x&1, but guaranteed to work regardless of how an int is represented;

Code:`int IsOdd(int x)`

{

while (x > 0) x -= 2;

while (x < 0) x += 2;

return x;

}

int IsEven(int x)

{

return !IsOdd(x);

}

- 03-14-2006DarrylQuote:

Originally Posted by**grumpy**

And since you brought up efficiency, if yours is passed a very large integer, how slow is that going to be? I would guess to slow for most practical purposes. - 03-14-2006laserlightQuote:

And since you brought up efficiency, if yours is passed a very large integer, how slow is that going to be? I would guess to slow for most practical purposes.

- 03-14-2006Dave_SinkulaQuote:

Originally Posted by**Darryl**

*grumpy*may have meant. - 03-14-2006DarrylQuote:

Originally Posted by**laserlight**

Code:`bool isOdd(int n) {return n&1;}`

bool isOdd(int n) {return n << (8*sizeof(int)-1) ;}

bool isOdd(int n) { bitset<sizeof(int)> b(n); return b.test(0);}

and for one's complement systems

bool isOdd(int n) { return abs(n)&1;}

- 03-14-2006Dave_Sinkula
Rethink this one too for ones' complement, and for CHAR_BIT != 8, and for padded integers (or is that one just a C possibility?).

Code:`bool isOdd(int n) {return n << (8*sizeof(int)-1) ;}`

- 03-14-2006grumpyQuote:

Originally Posted by**Dave_Sinkula**

- 03-14-2006Rashakil FolQuote:

Originally Posted by**7stud**

At least in the STL implementation that gcc uses, the modulo operator is in fact used.

http://gcc.gnu.org/onlinedocs/libstd...ce.html#l00883