• (cs)

    This is not the worst way I ever heard of to determine if a number is odd or even.

    That prize is awarded to a jolly chap whose meanderings during an interview were described to me by the interviewer.

    bool isOdd( unsigned number )
    {
      unsigned counter = 0;
    
      while( 1 )
      {
        if( counter == number )
          return false;
    
        counter++;
    
        if( counter == number )
          return true;
      }
    }

    Great, O(n) to find if n is odd... (Depending on the divide support in the CPU, the conventional method might be as heavy as O(log2(n)).)

  • someone (unregistered)

    let us follow isOdd(2)

    unsigned counter = 0; while( 1 ) if( counter == number ) return false; # 0==2

    counter++; #counter = 1
      
    if( counter == number ) return true; # 1==2 
    

    while( 1 ) # second round through the while loop if( counter == number ) return false; # 1==2

    counter++; #counter = 1
      
    if( counter == number ) return true; # 2==2 
    

    2 is odd

  • sb (unregistered) in reply to someone

    I can't tell if you are being sarcastic or not. Its amazing the amount of wtf's in wtf comments.

    I quite like that answer for isOdd, shows creativity, to hell with efficiency.

  • cyborg (unregistered) in reply to Steve The Cynic
    Steve The Cynic:
    Great, O(n) to find if n is odd... (Depending on the divide support in the CPU, the conventional method might be as heavy as O(log2(n)).)

    Hell no, for ints all you do is check the least significant bit and you're done! It's a constant time check - it really couldn't be easier. Having said that I have no idea if (x % 2 == 0) would be compiled to that if that is the mechanism you refer to.

  • Miriam (unregistered)
    bool isOdd(int n){
       return n / 2 < ((double) n) / 2
    }
    

    Do I get a 🍪 now?

  • (cs) in reply to Steve The Cynic
    Steve The Cynic:
    (Depending on the divide support in the CPU, the conventional method might be as heavy as O(log2(n)).)
    If your compiler isn't able to optimise i % 2 to i & 1 than your compiler is TRWTF.

    Edit: And cyborg beat me by 2 minutes! But his answer wasn't there when i pressed the quote-button!

  • Miriam (unregistered) in reply to Miriam
    bool isOdd(int n){
       return n / 2 < ((double) n) / 2;
    }
    

    Do I get a 🍪 now? I hate the fact that I always want to write in C-like Syntax even though I currently work with VB.NET at work. ARRRGH SEMICOLONS

  • someone (unregistered) in reply to sb

    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

  • Modulo (unregistered)

    Seriously, the modulo operator is overrated, isn't it? ;-)

  • RFox (unregistered) in reply to Steve The Cynic

    Yeah, and here he could have just done a binary search in the range [0,n] for an integer that, when multiplied by 2 gives the number in question...and if the search fails..well...then it's odd right? That would be O(log2(n)) for sure...much faster ;-)

    Steve The Cynic:
    This is not the worst way I ever heard of to determine if a number is odd or even.

    That prize is awarded to a jolly chap whose meanderings during an interview were described to me by the interviewer.

    bool isOdd( unsigned number )
    {
      unsigned counter = 0;
    
      while( 1 )
      {
        if( counter == number )
          return false;
    
        counter++;
    
        if( counter == number )
          return true;
      }
    }

    Great, O(n) to find if n is odd... (Depending on the divide support in the CPU, the conventional method might be as heavy as O(log2(n)).)

  • Guestimate (unregistered) in reply to someone
    someone:
    let us follow isOdd(2) 2 is odd
    That method will return True for every value but Zero, 'cause every value will be compared twice, using the same comparision. And as the counter is advanced before the second comparision that one determines the outcome (if it does not match, neither will the second-execuded comparision at the top).

    It looks like someone forgot a "counter ++" at the bottom of the while loop (between the comparisions)

  • Miriam (unregistered) in reply to someone
    someone:
    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

    What an oddball. How can you not believe in even numbers?

  • faoileag (unregistered) in reply to Miriam
    Miriam:
    [code]I currently work with VB.NET at work.
    Ooops. My sympathies. Here, have a 🍪!
  • Oddie (unregistered) in reply to someone
    someone:
    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

    Also doesn't work for negative numbers.

  • faoileag (unregistered)

    For websites there is only one correct way to implement zebra-striping:

    With a CSS selector: nth-child(2n)!

    That is the Discourse way, and of course Discourse is doing it right (tm)!

  • nmclean (unregistered) in reply to Oddie
    Oddie:
    someone:
    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

    Also doesn't work for negative numbers.

    Negative numbers will never be passed to it.

  • faoileag (unregistered) in reply to Oddie
    Oddie:
    someone:
    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

    Also doesn't work for negative numbers.

    All those unsigned keywords in the code sample somehow let me assume that that code snippet is not intended to be used with negative numbers...

  • SuomynonA (unregistered)

    This reminds me of one old joke:

    Three C coders write a function that takes an integer argument between 0 and 10 and returns 1 if argument is odd, 0 if it is even.

    Newbie coder writes this:

    int isOdd(int x)
    {
      if (x % 2 == 1)
        return 1;
      else
        return 0;
    }

    Second, more experienced coder writes this:

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

    Third one, the most experienced of them, writes this:

    int isOdd(int x)
    {
      static const int lookup_table[] = {0,1,0,1,0,1,0,1,0,1,0};
      return lookup_table[x];
    }
  • someone else (unregistered) in reply to Oddie
    Oddie:
    someone:
    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

    Also doesn't work for negative numbers.

    Good thing it only takes unsigned numbers.

  • nmclean (unregistered) in reply to SuomynonA
    SuomynonA:
    Third one, the most experienced of them, writes this:
    int isOdd(int x)
    {
      static const int lookup_table[] = {0,1,0,1,0,1,0,1,0,1,0};
      return lookup_table[x];
    }
    Not pictured: the code for the job that generated that code, and its configuration file.
  • (cs) in reply to someone
    someone:
    let us follow isOdd(2)

    unsigned counter = 0; while( 1 ) if( counter == number ) return false; # 0==2

    counter++; #counter = 1
      
    if( counter == number ) return true; # 1==2 
    

    while( 1 ) # second round through the while loop if( counter == number ) return false; # 1==2

    counter++; #counter = 1
      
    if( counter == number ) return true; # 2==2 
    

    2 is odd

    Definite oops. I left out the second counter++, my bad.

  • amomynous (unregistered) in reply to Oddie
    Oddie:
    someone:
    I was actually following the code of #436854 from stevethecynic. Manually following some code is a great way to get inspired in getting more ways to make it fail.

    His code will actually work if it has a "counter++;" before the end of the while(1) loop,

    Also doesn't work for negative numbers.

    It does, just wait for it to overflow.

  • (cs) in reply to no laughing matter
    no laughing matter:
    Steve The Cynic:
    (Depending on the divide support in the CPU, the conventional method might be as heavy as O(log2(n)).)
    If your compiler isn't able to optimise i % 2 to i & 1 than your compiler is TRWTF.

    Edit: And cyborg beat me by 2 minutes! But his answer wasn't there when i pressed the quote-button!

    Quite right, of course. The mention of divide support is a sort of pessimising worst case.

    Of course, I have seen a truly awful compiler, one that even on its most aggressive optimising settings would compile (on 8088/86) this:

      while( 1 )
      {
        /* ... */
      }
    to this:
       jmp loopend
    loopbegin:
        ; ...
    loopend:
        mov ax, 1
        cmp ax, 0
        jne loopbegin
    At the time, the version we had was 8 years old. It was still the live release version, and was still being sold. We changed to a different compiler (IIRC the new one was Aztec C) and boosted (software) floating point performance by a factor of three and reduced code size by about a fifth.

    Curiously on Aztec C I compiled some code that contained this line:

     x = inportb(N) * 256 + inportb(N+1);
    (where inportb() returns unsigned char) and found that it generated a mov instruction instead of a shift or multiply for the times-256...
  • (cs) in reply to Guestimate
    Guestimate:
    someone:
    let us follow isOdd(2) 2 is odd
    That method will return True for every value but Zero, 'cause every value will be compared twice, using the same comparision. And as the counter is advanced before the second comparision that one determines the outcome (if it does not match, neither will the second-execuded comparision at the top).

    It looks like someone forgot a "counter ++" at the bottom of the while loop (between the comparisions)

    Yeah, I forgot it... (red faced icon that I can't find in the BBCode guide)
  • (cs)

    So you might be inclined to say that I'm TRWTF, and today, based on my performance here, I'd be inclined to agree.

  • Bernie The Bernie (unregistered)

    WTF is happening to The Daily WTF? Only stories from more than a decade past to be found here nowadays?!

    Captcha: saepius. Latin saepe often, hence "more often" - fits well to this comment.

  • Neil (unregistered) in reply to no laughing matter
    no laughing matter:
    If your compiler isn't able to optimise i % 2 to i & 1 than your compiler is TRWTF.
    It's not always possible to do that optimisation, although declaring i unsigned, only comparing the result to zero, or having a sufficiently clever optimiser notice that i can't be negative at this point would suffice.
  • Pock Suppet (unregistered)

    Obviously you're all wrong. It should be

    bool function isOdd(int x) {
      return (x = 0) ? false : !isOdd(abs(x)-1)
    }
    because there's not a problem that can't be solved with recursion! It's the functional way!
  • fatfacemcfattypants (unregistered)

    To be fair change the language locale is a bad id, locale is for input and output.

    It might seems like a good idea to optimise and not have those I/O conversion layers but try making a large system without a uniform internal representation especially when it has to talk with other systems (no outer conversion layer necessitates an inner conversion layer).

  • (cs) in reply to sb
    sb:
    I can't tell if you are being sarcastic or not. Its amazing the amount of wtf's in wtf comments.

    I know, right? Everyone knows the correct answer is to take the number and post it through an API endpoint to a digital camera positioned above a wooden table. The point of the camera is to abuse the ALU for the odd/even logic.

    The output is then sent to a scanner which, for security reasons, has a wooden table on it. The table is situated to fall on anyone who attempts to disturb the scanner and make a great noise alerting people to the fact in the process.

    The scanner then forwards the now-secure output to the interwebs, where it will be implanted in a photo of a wooden table for steganographic purposes.

    Finally it is returned to the rendering algorithm to dictate the colour of the row (which will either be beech or oak) and judged fit-for-purpose by Heath Robinson, once it has been decoded.

  • Jim the Tool (unregistered) in reply to no laughing matter

    Hey my son is a compiler that isn't able to optimise i % 2 to i & 1, and let me tell you, it's no laughing matter!

  • anonymous (unregistered)

    Formats are hard.

    Reminds me of something I built in Access back when my simple time format was hh:mm. I wrote VB that made time boxes, on entry, highlight the first digit, and then proceed to overwrite digits as you entered them. It worked great.

    Fast forward to a computer upgrade which used a simple time format of h:mm. Needless to say, the VB totally failed and now, it clears the whole entry on your first keystroke (same as it would if you tabbed into the box normally, which was what I wanted to avoid).

    No biggie, I figure... just change the format code for that box to hh:mm.

    No can do.

    It changes hh:mm to "Simple time". Simple time is h:mm.

    I tried without luck to change it programmatically and finally gave up because typing the minutes portion is easier than trying to force Access to do what I want. And I'm not about to change the simple time format just because Access doesn't understand.

  • ¯\(°_o)/¯ I DUNNO LOL (unregistered)

    I would like to see Louis's implementation of FizzBuzz. inb4 people start posting fizzbuzz code

  • RandomGuy (unregistered) in reply to someone
    someone:
    2 is odd
    2 is the oddest prime!
  • airdrik (unregistered) in reply to RandomGuy
    RandomGuy:
    someone:
    2 is odd
    2 is the oddest prime!
    But 2 is even, and beside the fact that an even number is by definition not odd, every good programmer knows that no even number is prime.
  • cyborg (unregistered) in reply to airdrik
    airdrik:
    RandomGuy:
    someone:
    2 is odd
    2 is the oddest prime!
    But 2 is even, and beside the fact that an even number is by definition not odd, every good programmer knows that no even number is prime.

    No triple number is prime except 3.

    Really it's only the idea there's something special about "even" and "odd" beyond the fact every even number is a multiple of 2 that makes this an "odd" fact which it isn't given something very odd indeed would be going on if somehow a multiple of a prime - 2 - was also a prime given that kind of breaks the entire definition.

  • (cs)
    An Odd Way to Find Even Numbers:
    Fred S. never much cared for zebra striping, the UI pattern than was all the rage after Mac OS X launched in 2001.

    Nice try, but no. "zebra striping" existed well before 2001. It actually started on gasp stationary which is commonly referred to as "greenbar continuous stationary", "greenbar continuous feed", or just "greenbar".

    As for why Fred never cared for it, to each their own. Many people find it a simple, clear way of delineating between rows so that you can follow them across the table somewhat more easily than if you just rely on borders.

  • Kahomono (unregistered)

    Silly! It's obvious that the string will be longer (by one or two characters) than the original number if the original is odd, and shorter or the same length if the original is even.

    Regardless of the decimal separator character!

  • mpoly (unregistered)

    use Lingua::EN::Numbers qw(num2en); sub isodd {return (num2en shift) =~ /e.?$/}

  • foo AKA fooo (unregistered) in reply to Jim the Tool
    Jim the Tool:
    Hey my son is a compiler that isn't able to optimise i % 2 to i & 1, and let me tell you, it's no laughing matter!
    Sorry to hear that your son is not smart enough.
  • gallier2 (unregistered) in reply to SuomynonA
    SuomynonA:
    This reminds me of one old joke:

    Three C coders write a function that takes an integer argument between 0 and 10 and returns 1 if argument is odd, 0 if it is even.

    Newbie coder writes this:

    int isOdd(int x)
    {
      if (x % 2 == 1)
        return 1;
      else
        return 0;
    }

    Second, more experienced coder writes this:

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

    Third one, the most experienced of them, writes this:

    int isOdd(int x)
    {
      static const int lookup_table[] = {0,1,0,1,0,1,0,1,0,1,0};
      return lookup_table[x];
    }

    and the experienced one gets a kick in the nuts for providing the heaviest and the slowest solution.

    The 2 obvious solution get compiled in 1 and assembly instruction, the other one needs the load of an address (4 byte immediate or 8 byte immediate on a 64 bit machine) and a load base+index instruction, which has the side effect of loading the lookup_table into the cache which might evict more precious data. It annoys me always when algorithm are compared in a imaginary machine that knows nothing about registers, caches (lvl 1, 2 or 3), local memory, remote memory (on multi socket machines) etc.

  • nmclean (unregistered) in reply to abarker
    abarker:
    An Odd Way to Find Even Numbers:
    Fred S. never much cared for zebra striping, the UI pattern than was all the rage after Mac OS X launched in 2001.

    Nice try, but no. "zebra striping" existed well before 2001. It actually started on gasp stationary which is commonly referred to as "greenbar continuous stationary", "greenbar continuous feed", or just "greenbar".

    As for why Fred never cared for it, to each their own. Many people find it a simple, clear way of delineating between rows so that you can follow them across the table somewhat more easily than if you just rely on borders.

    To be fair, there is a difference between "be all the rage" and "exist".

  • mpoly (unregistered) in reply to mpoly

    works 99% of the time - so good enough for all practical purposes

    captcha: damnum

  • nmclean (unregistered) in reply to gallier2
    gallier2:
    and the experienced one gets a kick in the nuts for providing the heaviest and the slowest solution.
    https://www.youtube.com/watch?v=xECUrlnXCqk
  • planB (unregistered) in reply to Kahomono
    Kahomono:
    Silly! It's obvious that the string will be longer (by one or two characters) than the original number if the original is odd, and shorter or the same length if the original is even.

    Regardless of the decimal separator character!

    Cann't there be a 1000-seperator when you convert it to string? ( "1,000" as in 1000 )?

  • gallier2 (unregistered) in reply to nmclean
    nmclean:
    gallier2:
    and the experienced one gets a kick in the nuts for providing the heaviest and the slowest solution.
    https://www.youtube.com/watch?v=xECUrlnXCqk

    Yes, I know, but I am an humourless git.

  • New way (unregistered)

    You don't need a double cast...

    bool isOdd(int n) { return n >= 0 ? (n/2 == (n-1)/2) : isOdd(-n);
    }

    Which, unlike the (n & 0x1) or the (n % 2) solution, actually guarantees[0] the correct answer for n < 0. C is not a two-complement language, even though it kinda is.

    [0] Well, nearly. isOdd(INT_MIN) will recurse infinitely. Yay, C.

  • deleted (unregistered) in reply to nmclean
    nmclean:
    abarker:
    An Odd Way to Find Even Numbers:
    Fred S. never much cared for zebra striping, the UI pattern than was all the rage after Mac OS X launched in 2001.

    Nice try, but no. "zebra striping" existed well before 2001. It actually started on gasp stationary which is commonly referred to as "greenbar continuous stationary", "greenbar continuous feed", or just "greenbar".

    As for why Fred never cared for it, to each their own. Many people find it a simple, clear way of delineating between rows so that you can follow them across the table somewhat more easily than if you just rely on borders.

    To be fair, there is a difference between "be all the rage" and "exist".

    To be accurate, every frickin' computer installation back in the days of batch accounting programs used green-bar or grey-bar to aid in making sense of tabulated output. That was the default form loaded on the printer, thus every print job used it. I would say that qualifies as "all the rage".

    With emphasis on "rage" whenever the printer jammed.

    My name is 'Tristique' and I am a young college graduate who utterly rejects the idea that anything existed before I was born. Including grey-bar continuous forms.

  • GWO (unregistered)

    You don't need a double cast...

    bool isOdd(int n) { return n >= 0 ? (n/2 == (n-1)/2) : isOdd(-n); }

    Which, unlike the (n & 0x1) or the (n % 2) solution, actually guarantees[0] the correct answer for n < 0. C is not a two-complement language, even though it kinda is.

    [0] Well, nearly. isOdd(INT_MIN) will recurse infinitely. Yay, C.

  • (cs) in reply to Jim the Tool
    Jim the Tool:
    no laughing matter:
    If your compiler isn't able to optimise i % 2 to i & 1 than your compiler is TRWTF.
    Hey my son is a compiler that isn't able to optimise i % 2 to i & 1, and let me tell you, it's no laughing matter!
    Would have worked better if you had learned the correct button is always the quote button! (i simulated that for you, daddy!)

Leave a comment on “An Odd Way to Find Even Numbers”

Log In or post as a guest

Replying to comment #:

« Return to Article