Finding out if int is even

Hi,
I’m trying to find out if an int is even or odd, I’ve read that modulus is slow in CUDA and I can’t seem to get it to work, is there anyway of doing this without modulus?
I was thinking of finding out what the last digit of the int and then checking to see what it is but I can’t seem to find a way to do this either…
any help would be great

Hi,

this could work:

if (int & 0x1)

   // odd

if (! (int & 0x1))

  // even

Simple as:

if (i & 1) {

// odd

} else {

// even

}

I think the compiler is able to make this optimization when you use modulus with a constant. Please, share if you discover something.

in case you don’t know of it already: http://en.wikipedia.org/wiki/Two%27s_complement

(it’s more complicated than if (x & 1) if you need to support negative numbers, but it’s certainly not impossible)

I use this for CPU code, although I never tried it on the GPU.

typedef struct

{

 union

 {

  unsigned int n;

  struct

  {

   unsigned lsb :1;  // The least-significant bit; will give the parity

   unsigned oBits :30; // Other useless bits

   unsigned msb :1;  // The most significant bit; won't be needed here

  };

 };

} intSplitter;// Not a very inspired name

intSplitter x = whatever;

if(x.lsb)

	// Odd

if(!x.lsb)

	// Even

There might be some obscure problems with this code that I haven’t found yet.

i think this also applies for negative numbers.

Yeah, the table at Wikipedia supports that assumption … I’m not sure anymore though :)

Yeah, I am super-obviously wrong (and now I feel very dumb to boot). Ignore me when I answer technical questions in the middle of the night.