Advertisement

Odd or even?

Started by August 03, 2002 04:29 PM
8 comments, last by Zealot 22 years, 6 months ago
Does anyone have a way to determine if a number is odd or even? En taro Adun! Doom to all who threaten the homeworld! *Protoss Zealot - Starcraft*
----------------------------------------------------------You know, I might as well go ahead and say I can't fix the problem... because that's when I figure out how.
Test if the first bit is set. If it is set then the number is odd, otherwise it is even.
Advertisement
A number n (I''ll stick to integers) is even if n mod 2 = 0, and odd if n mod 2 = 1 (these are the only two possibilities, so of course the first test can just be negated for odd). In C (for example), this is n%2 == 0 (even), or n%2 == 1 (odd).

Miles
yes,

one method is:

if (number MODULO 2) == 1
then
number is odd.

in C++:

if ((number % 2) == 1)
cout << "number is odd";



schiggl


  int n;if (n & 1)  // number is odd  
Thanks!

En taro Adun!
Doom to all who threaten the homeworld!
*Protoss Zealot - Starcraft*
----------------------------------------------------------You know, I might as well go ahead and say I can't fix the problem... because that's when I figure out how.
Advertisement
um... Miles... don''t the terms odd and even only make sense in relation to integers?

Anyho, the bit test is mucho faster than using modulus, so stick to that.
Mathematically speaking, they do.

But a float can have a value 2.
so it would be a "integer" in mathamatics

Bugle4d
~V'lionBugle4d
will the bit test also work with signed integers? negative numbers have inverted bits (2s complement).

a2k
------------------General Equation, this is Private Function reporting for duty, sir!a2k
Yes, it will work for negative integers also. Any positive even number will have the LSB set to 0. To negate this number using two''s complement, first invert all bits; LSB is now 1. Then you add one, and turn this one into a zero again.

This topic is closed to new replies.

Advertisement