I am a little frustrated by this I am sure that there is an easy way to do this?
I am a little frustrated by this I am sure that there is an easy way to do this?
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
Last edited by whiteflags; 01-02-2012 at 04:44 AM. Reason: cide correction
All integers are stored as binary values... bit 0, is always a 1 for odd numbers, only even numbers are divisible by 2.Code:int number; number = 42; if ((number & 1) == 0) puts("Divisible by two");
So... if bit0 = 0 the number is divisible by 2.
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.
Hope is the first step on the road to disappointment.
Ok... how about...
Code:if ( ! (num - ((num >> 1) << 1))) puts("Yup"); else puts("Naaaa");
Last edited by CommonTater; 01-02-2012 at 05:42 AM.
I don't work with floating point a lot, but I think this would work?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
Last edited by DeadPlanet; 01-02-2012 at 06:01 AM. Reason: Doublifying my casts
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; }
Whoever writes the fanciest program gets a cookie.
Originally Posted by The Jargon File
I like cookies...
Code:puts(num - ((num >> 1)<<1) ? "No" : "Yes");
CommonTater is in the lead.
Originally Posted by The Jargon File
Oh wait wait...Code:const char* answer[] = {"Yes", "No"); puts(answer[num&1]);
That's better.Code:puts("Yes\0No"+((num&1)<<2));
Edit: Aaargh, got it this time.
Last edited by iMalc; 01-02-2012 at 02:03 PM.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Except when they aren't, of course.
I win.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; }
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..
Last edited by Libpgeak; 01-03-2012 at 03:55 AM.