# Thread: How do I find if a number is exactly divisable by 2?

1. ## How do I find if a number is exactly divisable by 2?

I am a little frustrated by this I am sure that there is an easy way to do this? 2. Code:
```double number = whatever / 2.0;
double wholepart;
double fracpart;
wholepart = modf(number, &fracpart);
if (fracpart == 0.0)
divisible
else
not

int number = whatever % 2;
if (number == 0)
divisible
else
not``` 3. Code:
```int number;

number = 42;

if ((number & 1) == 0)
puts("Divisible by two");```
All integers are stored as binary values... bit 0, is always a 1 for odd numbers, only even numbers are divisible by 2.
So... if bit0 = 0 the number is divisible by 2. 4. Nice. No effort at all on the OP's part, and he has two options already. Guess I may as well round this out:
Code:
```r = num / 2;
if( r * 2 == num )
Yay!
else
Nay!```

Quzah. Code:
```if ( ! (num - ((num >> 1) << 1)))
puts("Yup");
else
puts("Naaaa");``` 6. Code:
```#include <limits.h>
#include <math.h>

...

int power;

power = log( (double) UINT_MAX + 1 ) / log( 2.0f ) - 1;

if( ( num << (power - 1) ) >> (power - 1)  )
//Odd
else
//Even```
I don't work with floating point a lot, but I think this would work? 7. or
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc,char *argv[])
{
double x;
int a;
int b;

x = 5.0;
x = fmod(x,2);
printf("%d\n",x == 0.0);
x = 4.0;
x = fmod(x,2);
printf("%d\n",x == 0.0);
x = 4.0000001;
x = fmod(x,2);
printf("%d\n",x == 0.0);

a = 5;
b = a % 2;
printf("%d\n",b==0);
a = 4;
b = a % 2;
printf("%d\n",b==0);

return 0;
}``` 8. Whoever writes the fanciest program gets a cookie. Code:
`puts(num - ((num >> 1)<<1) ? "No" : "Yes");` 10. CommonTater is in the lead. 11. Code:
```const char* answer[] = {"Yes", "No");
Oh wait wait...
Code:
`puts("Yes\0No"+((num&1)<<2));`
That's better.

Edit: Aaargh, got it this time. 12. Originally Posted by iMalc Code:
`puts("Yes\0No"+((num&1)<<2));`
I'll give you the lead after that one...

(Darn, I really wanted that cookie!) 13. Originally Posted by CommonTater All integers are stored as binary values...
Except when they aren't, of course.

Code:
```#include<stdio.h>
int divisible_by_two(long int data)
{
return !(data % 2L);
}
int main(int argc, char** argv)
{
char* errc;
while(*(++argv))
printf("%s is%s divisible by two\n", *argv, "\0 not" + !(divisible_by_two(strtol(*argv, &errc, 0)) - !!*errc));
return 0;
}```
I win. 14. Is there a possibility to swap the integer, shift it left, and watch the carry flag? That's the most fancy way i can imagine...
EDIT: Why don't use the parity flag.. 15. Originally Posted by gardhr Except when they aren't, of course.
Riiiiiight. there's one of them in everyone's livingroom.

I win.
Not up to you... this was Babcock's idea...
He gets to judge. Popular pages Recent additions 