Advertisement

Best way to find Even/Odd

Started by September 10, 2000 11:33 PM
17 comments, last by Esap1 24 years, 3 months ago
quote: Original post by Stoffel

OnTopic:
(n & 1) should be faster than (n % 2). Some compilers might optimize it to the same, but I''m never sure what the % operator boils down to. I find the first more readable, but that''s just a point of personal preference.


integer modulo is one of the most expensive operations on most CPU''s. (n&1) would be a MUCH better choice.



inline bool isOdd(int x) {
return (x&1);
}

-- or --

#define IS_ODD(x) (bool)(x&1);

Whichever way you prefer!



Edited by - Buster on September 12, 2000 5:18:31 PM
Advertisement
The modulus operator is a speed killer if used in an inner loop. The actual definition for modulus is "The result of the modulus operator (%) is the remainder when the first operand is divided by the second." So, by definition, modulus uses a division, which should be avoided whenever possible.

If you are doing a modulus by a power of two, instead & the first number with one minus the second. So, instead of:
int i=number%16; do
int i=number&15; which will give you the same result.

Note that visual c++ 6.0 will do this optimization for you where possible.

PreManDrake
Thank you Premandrake! I was just about to post a question regarding a similar problem (Optimizing the % operator). This clears it up for me before the post is made.

Thanks again,

Jumpster
Regards,JumpsterSemper Fi
Stoffel: You are right, but I was very upset, and usually something like that would he deserve a post, I know, I appoligize. I would of jumped on anyone like that, though I still think that spelling isnt a big deal, of course I know how to spell standard, but if you new what I was talking about, why did u even have to say anything, whateva, it all good.
Hi!
Just a little not:
I think there is no problem if people correct other peoples spelling errors(Yep please correct my if neccessary) BUT they should correct other people if it is obvious that they don´t know how to spell a word not if they made just a typo....

P.s.:Spelling correction is not evil....Some threads are so full of errors that one shouldn´t answer....

Greets,XBTC!


Advertisement
Hoo neads speling wen yoo ar a kumputor programmar?

Ih tohnt nau... mizpheling iz cohl...
----------------------------------------http://www.sidema.be----------------------------------------
lighten up on the guy will ya, just cause he corrected someones spelling doesnt mean hes a f'in asshole son of a sheepdog shagging whore with the an IQ of someit i dredged outta my nose. no not at all hes more like a ......(censored)

Edited by - zedzeek on September 15, 2000 6:44:04 AM

This topic is closed to new replies.

Advertisement