• Sean (cs)

    I'd like to see his power raising and factorial methods.

  • dpm (cs)

    Don't blame the original programmer.  Everyone knows that subtracting is much faster than dividing.


    ok

    dpm

  • Manni (cs)

    Many thanks to Alex for not adding on to the intro for that WTF. Honestly, the code alone was enough for me to shoot milk out of my nose, which was weird because I was drinking Cherry Coke at the time....

  • gonzo (cs) in reply to Manni
    Manni:
    Honestly, the code alone was enough for me to shoot milk out of my nose, which was weird because I was drinking Cherry Coke at the time....


    LOL

    As for the OP, the real WTF is obviously the usage of the Solaris C++ compiler.
  • Oliver Klozoff (cs)

    Good god...

    Even before I knew I could use % to do remainder calculations (I just wanted the remainder. "Modulus"? Never heard of that before... what's it do?), I wrote the equivalent to this code:

    int result = value / divisor;
    nit remainder = value - (result * divisor);

    And when I first explored C after using Pascal for years (where integer division is 'div' and modulus is 'mod'), I easily understood '/' for division, but even before I learned that '%' was modulus, I found this standard function:

    printf("Dividing %d by %d:\n", value, divisor);
    div_t r = div(value, divisor);
    printf("Result = %d\n", r.quot);
    printf("Remainder = %d\n", r.rem);


    And if anybody's wondering, I was self-taught in Pascal and C, which is why it took so long before I learned about '%'.

  • kipthegreat (cs) in reply to Oliver Klozoff
    Oliver Klozoff:
    Good god...

    Even before I knew I could use % to do remainder calculations (I just wanted the remainder. "Modulus"? Never heard of that before... what's it do?), I wrote the equivalent to this code:

    int result = value / divisor;
    nit remainder = value - (result * divisor);

    And when I first explored C after using Pascal for years (where integer division is 'div' and modulus is 'mod'), I easily understood '/' for division, but even before I learned that '%' was modulus, I found this standard function:

    printf("Dividing %d by %d:\n", value, divisor);
    div_t r = div(value, divisor);
    printf("Result = %d\n", r.quot);
    printf("Remainder = %d\n", r.rem);


    And if anybody's wondering, I was self-taught in Pascal *and* C, which is *why* it took so long before I learned about '%'.



    I remember doing something like this on my first programming language.. TI-83's version of BASIC.  :)

    I don't remember the syntax so I'll use C++ style:

    <font size="2"><span style="font-family: Courier New;">double tmp = value / divisor;&nbsp; //where this is floating point division on a TI-83</span></font>
    <font size="2"><span style="font-family: Courier New;">int result = ipart(tmp);&nbsp;&nbsp; // ipart() is "integer part", the part before the decimal (similar to floor())</span></font>
    <font size="2"><span style="font-family: Courier New;">int remainder = round( divisor * fpart(tmp) );&nbsp;&nbsp; //where fpart() is fraction part.. the number starting at the decimal point.</span></font>


  • Oliver Klozoff (cs)

    Let's say, for the sake of argument, that you don't even know about the divide operator (/);
    here's an implementation that works for non-negative (>=0) dividends and positive (>0) divisors (it would be simple to modify it in order to support the full range of signed integers).

        // get the quotient (getmodulus=false) or remainder (getmodulus=true)
        static int divide(int dividend, int divisor, bool getmodulus) {
            // this code is C#, but should work as C if you adjust the exception stuff to something appropriate
            if (dividend < 0 || divisor < 0) { throw new Exception("too complicated"); }
            if (divisor == 0) { throw new Exception("Division by zero"); }
            if (dividend < divisor) return getmodulus ? dividend : 0;
            int quotient = 0;    // if dividend >= divisor, there is at least one.
            while (dividend >= divisor) {
                int quot2 = 1;
                int divisor2 = divisor;
                while (divisor2 <= (dividend >> 1) ) {
                    quot2<<=1;
                    divisor2<<=1;
                }
                dividend -= divisor2;
                quotient |= quot2;
            }
            if (getmodulus) return dividend;
            return quotient;
        }


    In fact, a function much like this one is often embedded in programs compiled for a processor that has no divide instruction (which is actually the case for a majority of RISC-type processors).

    Golf at will, guys!

  • CornedBee (cs)

    You know what the problem with this story is? It's too obvious. When I saw the post title, I already knew what the code would be.

    That it's at a defense contractor scares me a little, though.

  • Joost_ (cs) in reply to CornedBee

    <span style="font-family: courier new;">Pfft. I used to work at Lockheed where we would use lookup tables to avoid calculation of modulo. </span>

    <span style="font-family: courier new;">Vector generateModuloLookup(int table, int max) {</span>
    <span style="font-family: courier new;">  Vector lookup = new Vector();<br> </span><span style="font-family: courier new;">  for(int i = 0; i &lt; max; i++)<br>   {<br>     Integer value = new Integer(i * table);<br style="font-family: courier new;"> </span><span style="font-family: courier new;"></span><span style="font-family: courier new;">    lookup.Add(value);<br>   }<br>   return lookup;<br style="font-family: courier new;"> </span><span style="font-family: courier new;"></span><span style="font-family: courier new;">}<br> <br> int lookupModule(Vector lookup, Integer number)<br> {<br>   </span><span style="font-family: courier new;">return lookup.indexOf(number);</span>
    <span style="font-family: courier new;"><br> int lookupModulo(Vector lookup, int number)<br> {<br>   return lookupModulo(new Integer(number));<br> }<br> </span>

  • mazurek (cs) in reply to Joost_
    Joost_:
    <span style="font-family: courier new;">Pfft. I used to work at Lockheed where we would use lookup tables to avoid calculation of modulo. </span>


    Now that's the real wtf!!! My eyes - the googles, they're not helping!!!
  • adv (cs)

    I'll have to admit to having made this mistake.

    Of course, I was taking my first programming course in high school at the time...

  • Darax The Good (cs) in reply to Sean

    something similar-but worse.  Anything to avoid spinning up the FPU.  This was shoved into something quite a bit more complex-and of course the variable names were j and z instead of value and remainder-so it took a bit to figure out exactly what was going on.

    void divide(int x, int y) // x/y

    {

       int value=0, remainder;

       While (x > y)

        {

          value++;

          x-=y;

       }

    remainder = x;

    }

  • emurphy (cs)

    At least it was only operating on integers, otherwise it could also get into an infinite loop when value/divisor is so large that (value-divisor) gets rounded to (value).

  • Just (cs) in reply to emurphy

    I could have sworn that C++ only allows for one implicit conversion, not 3 as described in the WTF. Is my memory failing, or is this a Solaris compiler extension (highly unlikely), or is the WTF submitter mistaken?

    BTW, I was forced to register to post this, as the spam tester thing that non-registered posters have to go to (where you need to enter the characters displayed in an image) wasn't working. I just got a red x. Is this a deliberate ploy to get more registered users? ;)

  • Kevin S (cs) in reply to Darax The Good

    Hey everyone! Long time reader, but only now really have something that is somewhat relevant =P  I'm currently in a Senior Design course, and we are having to create a BREW game for a cellphone.  The class is divided up into small groups, and each group has their own seperate game they are creating, and our 4 person group was to create a cell phone represenation of Trogdor. But anyway, one of our group members has basically been useless the entire term, but recently we gave him one simple task to complete in a week.  He was to make it where the player was rewarded with a free man ("Mans") every 50 points, and to also give 30 points at the end of every level.  This is what he came up with, and logged 5 hours to create it.  Its called at the end of every level.  We of course just rewrote it and decided we were better off if he stuck to busy work.

    //extra man every 50 points
    #define BONUS_MAN 50
    score = pMe->nScore;

    while (score > BONUS_MAN)
    {
        score -= BONUS_MAN;
    }
    if((score + 30) > BONUS_MAN)
    {
        pMe->nMans += 1;
    }
    score = 0;
    pMe->nScore += 30;

  • nickf (cs) in reply to Kevin S

    called only at the end of each level? but i want my extra mans now! i also like how he sets score = 0 for no apparent reason. Also, what happens if you're so good that you score over 100 points in a level?
    all that aside, the REAL wtf there is that he didn't use "pMe->nMans++;"


    (on a side note - i had to register as well - the anti-spam protection seems to have upgraded itself to anti-post protection. and since i'm on the topic of bagging the forum software, i can't click in the textarea to type a reply, i have to click somewhere else and tab my way through all the emoticons to get there. can't click on any emoticons either...)

  • mjonhanson (cs)

    That's nothing.  When I was a young 'snapper programmer, we didn't have operators to do addition, all we had was a stick and some sand.

  • Drak (cs) in reply to mjonhanson

    Is the problem with the code so obvious to everyone? I've not seen any of the usual comments aout how it is broken, so I'll start...

    Try 9 for value and 5 for divisor... I guess you get an endless loop?

    So this function should be called makeSureNumberIsWhollyDivisibleOrElseGoIntoComa() ?

    Drak

  • anonymous_ (cs) in reply to Drak
    Drak:

    Is the problem with the code so obvious to everyone? I've not seen any of the usual comments aout how it is broken, so I'll start...

    Try 9 for value and 5 for divisor... I guess you get an endless loop?

    So this function should be called makeSureNumberIsWhollyDivisibleOrElseGoIntoComa() ?

    Drak


    value is 9, divisor is 5

    remainder is set to 9


    remainder is not 0, enter while

    remainder is > divisor, take if

    remainder is 9 - 5 (which is 4)

    test while again

    remainder is not 0

    remander is 4, divisor is 5

    take else

    break


    done




    wait.. what?  Do not allow replies to this post check box?  and the captcha image isn't showing up...

  • raph (cs) in reply to Oliver Klozoff

    Oliver Klozoff:
    Let's say, for the sake of argument, that you don't even know about the *divide* operator (/);
    here's an implementation that works for non-negative (>=0) dividends and positive (>0) divisors (it would be simple to modify it in order to support the full range of signed integers).

        // get the quotient (getmodulus=false) or remainder (getmodulus=true)
        static int divide(int dividend, int divisor, bool getmodulus) {
            // this code is C#, but should work as C if you adjust the exception stuff to something appropriate
            if (dividend < 0 || divisor < 0) { throw new Exception("too complicated"); }
            if (divisor == 0) { throw new Exception("Division by zero"); }
            if (dividend < divisor) return getmodulus ? dividend : 0;
            int quotient = 0;    // if dividend >= divisor, there is at least one.
            while (dividend >= divisor) {
                int quot2 = 1;
                int divisor2 = divisor;
                while (divisor2 <= (dividend >> 1) ) {
                    quot2<<=1;
                    divisor2<<=1;
                }
                dividend -= divisor2;
                quotient |= quot2;
            }
            if (getmodulus) return dividend;
            return quotient;
        }


    In fact, a function much like this one is often embedded in programs compiled for a processor that has no divide instruction (which is actually the case for a majority of RISC-type processors).

    Golf at will, guys!

    I usedc to do soemthing similar on a Marconi Myriad computer, except that I used right shifts instead of left. The operation times were add/sub 2 microsecs, multiplye 24 microsecs, divide 48 microsecs. Multiplication and division by certain special numbers, e.g. 10 which only has two bits set, was faster by shift-and-add/subtract than by hardware multiplication/division.

    Incidentally, division was rounded fractional division, not integer truncated division, so even after a hardware division you still had to do a 1-place shift and check for a negative remainder.

  • trollable (cs)

    My Sun5 is unplugged and i don't remember if the 68000 supports neither the modulo instruction nor the div one. A possible guess is the pasted code may run faster on the old Solaris/68000 combination. The fact it is C++and/or Solaris doesn't really matter, the CPU does.



  • haveworld (cs) in reply to Drak
    Drak:

    Is the problem with the code so obvious to everyone? I've not seen any of the usual comments aout how it is broken, so I'll start...

    Try 9 for value and 5 for divisor... I guess you get an endless loop?

    So this function should be called makeSureNumberIsWhollyDivisibleOrElseGoIntoComa() ?

    Drak



    Copy the code and test with those values and come back and tell us if you went into a Coma...
  • stevekj (cs)

    OK, so I can't think of how this code could result in an infinite loop.  If the divisor were zero, the code would generate a divide-by-zero exception on most systems.  Even a negative (non-zero) divisor would have to result in a wraparound condition eventually, given a finite size of integer, which would terminate the loop after a while (depending on size of integer, magnitude of divisor, and speed of CPU).

  • trollable (cs) in reply to stevekj
    stevekj:
    OK, so I can't think of how this code could result in an infinite loop.  /.../ (depending on size of integer, magnitude of divisor, and speed of CPU).

    Solaris was designed for the 68000, 8MHz. The loop is about 15 cycles (raw approximate). The value is an epoch, the divisor is not specified but is probably small. Now some math is required. The OP should have mention the hardware :(
  • Charlie Marlow (cs) in reply to stevekj

        It was not specified in the original post, but if the divisor ends up being a negative number during all of those conversions, it will result in an infinate loop.

  • Phill (cs) in reply to mjonhanson

    mjonhanson:
    That's nothing.  When I was a young 'snapper programmer, we didn't have operators to do addition, all we had was a stick and some sand.

    You were lucky. I could only have dreamed of having a stick and some sand. All I had for addition was a concrete wall to bang my head against while my father whipped me with his belt.

  • XoK (cs)

    What about ...

    int remainder = value - (floor(result) * divisor);

    No " % " thing :)

     

    Alex Papadimoulis:

    int result=value/divisor;
    int remainder=value%divisor;

     

  • Disgruntled DBA (cs) in reply to Phill
    Phill:

    mjonhanson:
    That's nothing.  When I was a young 'snapper programmer, we didn't have operators to do addition, all we had was a stick and some sand.

    You were lucky. I could only have dreamed of having a stick and some sand. All I had for addition was a concrete wall to bang my head against while my father whipped me with his belt.



    Luxury.

    When I was a junior programmer, the Senior programmer would line us up in rows of 8, and club us over the head to punch out holes in the formation.  The surviving members would have to run in unison into the reader machine, in order to load the program.
  • luke727 (cs)

    As that other guy said, the forum is broken.  When not logged in the captcha images are not showing so you can't post anonymously, and now there is a "Do not allow replies to this post" checkbox.  A real WTF in itself as generally a forum is a place to exchange information and ideas.  I have been here a w<font style="BACKGROUND-COLOR: #ffffff">hil</font>e (anonymously) and agree with apparently many other people that this forum software...what is the word I'm looking for...oh yeah...

    <font style="BACKGROUND-COLOR: #000000" face="Arial" color="#ff0000" size="72"><strong><em><u>SUCKS!!!</u></em></strong></font>

    Anyway, back on topic.  This is not really a WTF.  The guy knew what he was doing and it is intentional; the other people just don't understand how brillant it is.  A good practice when developing software is to add a few delay loops here and there, i.e. something like

    for(int i = 0; i < 1000000; i++)
    {
       int wtf = i * (i + 1) / 2;
    }

    Then every so often you can just take one of the loops out and claim you optimized it.  Everyone will be in awe of your awesomeness (naturally).

    As I sit here ready to post it I notice that there really is no Preview button (I thought it was just a joke or something).  This is quite possibly the biggest WTF of them all.  I cannot think of any forum that I have used anywhere anytime that did not have some kind of Preview option available.  I had to edit the HTML by hand for the code, and if the formatting of this post does not come out right I will be forced to kick a puppy.

    I pray there is nothing below this line...

  • luke727 (cs) in reply to luke727

    That is supposed to be big red text on black background "SUCKS!!!", but it came out regular size black on black (further proving my point).

    The broken image on the bottom is more disturbing, though.  I dragged one of the menu placeholders (whatever the fuck they are called, the three-dot thing on the left of the menu strips) into the text box.  It results in a resizable bitmap in the text area.  My only question is WTF?

  • stevekj (cs) in reply to trollable
    trollable:
    stevekj:
    OK, so I can't think of how this code could result in an infinite loop.  /.../ (depending on size of integer, magnitude of divisor, and speed of CPU).

    Solaris was designed for the 68000, 8MHz. The loop is about 15 cycles (raw approximate). The value is an epoch, the divisor is not specified but is probably small. Now some math is required. The OP should have mention the hardware :(


    OK, with a bit of quick math it looks like it could easily run for an hour or so.  Not quite an infinite loop, but could easily be mistaken for one by a tester!

  • mjonhanson (cs) in reply to Disgruntled DBA
    Disgruntled DBA:
    Phill:

    mjonhanson:
    That's nothing.  When I was a young 'snapper programmer, we didn't have operators to do addition, all we had was a stick and some sand.

    You were lucky. I could only have dreamed of having a stick and some sand. All I had for addition was a concrete wall to bang my head against while my father whipped me with his belt.



    Luxury.

    When I was a junior programmer, the Senior programmer would line us up in rows of 8, and club us over the head to punch out holes in the formation.  The surviving members would have to run in unison into the reader machine, in order to load the program.


    Machine readers were something only in the data centers of the rich.  Their Pinkertons used to come into our data center and tear up all the paper tape we made with our teeth.
  • stevekj (cs) in reply to Charlie Marlow
    Charlie Marlow:
        It was not specified in the original post, but if the divisor ends up being a negative number during all of those conversions, it will result in an infinate loop.


    Are you sure?  Bear in mind that in normal signed integer arithmetic, which is what this looks like, a series of additions will eventually wrap around to a negative number... and although the hardware will probably detect this overflow condition, the software usually doesn't.
  • voodooc (cs) in reply to mjonhanson
    mjonhanson:
    Disgruntled DBA:
    Phill:

    mjonhanson:
    That's nothing.  When I was a young 'snapper programmer, we didn't have operators to do addition, all we had was a stick and some sand.

    You were lucky. I could only have dreamed of having a stick and some sand. All I had for addition was a concrete wall to bang my head against while my father whipped me with his belt.



    Luxury.

    When I was a junior programmer, the Senior programmer would line us up in rows of 8, and club us over the head to punch out holes in the formation.  The surviving members would have to run in unison into the reader machine, in order to load the program.


    Machine readers were something only in the data centers of the rich.  Their Pinkertons used to come into our data center and tear up all the paper tape we made with our teeth.


    Right.

    When I was a young lad, we had to get to work at 3 AM, 2 hours before we went to bed, where we would have to sit in six status meetings with fifteen other coworkers and explain all the projects we were working on to a parapalegic baboon with down's syndrome.  Our company was too poor to afford paper tape, so we had to carve little 1's and 0's into the bones of our own forearms with a staple remover.  Applications were 'interpreted' by a washed up witch doctor who had escaped from the Dominican Republic after killing twelve people with a blunt instrument.  We would have to cut off our forearms, boil the flesh off them, and give them to 'Doc', who would find meaning in our bones.  Instead of coffee, we had to lick the varnish off our desks, and instead of a lunch break, we got to drink our own boiled-off flesh.

    And when we got home, our dad would cut us in two with a bread knife and dance about on our graves singing hallelujah.

    vc
  • Charlie Marlow (cs) in reply to stevekj

    That is true. I guess that, like the other case, it would take so long to run that it would appear to be stuck. Of course, the answer received from such a situation for the remainder would be a little off.

  • Richard Nixon (cs) in reply to voodooc
    voodooc:
    mjonhanson:
    Disgruntled DBA:
    Phill:

    mjonhanson:
    That's nothing.  When I was a young 'snapper programmer, we didn't have operators to do addition, all we had was a stick and some sand.

    You were lucky. I could only have dreamed of having a stick and some sand. All I had for addition was a concrete wall to bang my head against while my father whipped me with his belt.



    Luxury.

    When I was a junior programmer, the Senior programmer would line us up in rows of 8, and club us over the head to punch out holes in the formation.  The surviving members would have to run in unison into the reader machine, in order to load the program.


    Machine readers were something only in the data centers of the rich.  Their Pinkertons used to come into our data center and tear up all the paper tape we made with our teeth.


    Right.

    When I was a young lad, we had to get to work at 3 AM, 2 hours before we went to bed, where we would have to sit in six status meetings with fifteen other coworkers and explain all the projects we were working on to a parapalegic baboon with down's syndrome.  Our company was too poor to afford paper tape, so we had to carve little 1's and 0's into the bones of our own forearms with a staple remover.  Applications were 'interpreted' by a washed up witch doctor who had escaped from the Dominican Republic after killing twelve people with a blunt instrument.  We would have to cut off our forearms, boil the flesh off them, and give them to 'Doc', who would find meaning in our bones.  Instead of coffee, we had to lick the varnish off our desks, and instead of a lunch break, we got to drink our own boiled-off flesh.

    And when we got home, our dad would cut us in two with a bread knife and dance about on our graves singing hallelujah.

    vc


    Does anyone (besides the "people" who write this crap) still think these types of "jokes" are even the slightest bit amusing? It just gets worse and worse the more idiots who pile on.

    Sincerely,

    Richard Nixon
  • voodooc (cs) in reply to Richard Nixon
    Richard Nixon:


    Does anyone (besides the "people" who write this crap) still think these types of "jokes" are even the slightest bit amusing? It just gets worse and worse the more idiots who pile on.

    Sincerely,

    Richard Nixon


    It's an Idiot Orgy!  Thank you for contributing your genetic material.

    Hm, how many limbs do you have?  And do you like to wander around the African veldt?  And how big is your forehead?  I only ask because you remind me of someone I used to work for.

    vc
  • hank miller (cs) in reply to luke727
    luke727:
    [typical rant about this forum]

      My only question is WTF?



    Welcome to the club.   The rest of us have been seen the same problems.

    There is good reason there is no preview button - anything previewed NEVER showed up the same when posted, while if you didn't preview (just trusting to the devil) once in a while things look like you want them to.

    The only good part about this is people will believe me when I blame my grammar and spelling errors on the forum.   Anywhere else they blame me.
  • Richard Nixon (cs) in reply to voodooc
    voodooc:
    Richard Nixon:


    Does anyone (besides the "people" who write this crap) still think these types of "jokes" are even the slightest bit amusing? It just gets worse and worse the more idiots who pile on.

    Sincerely,

    Richard Nixon


    It's an Idiot Orgy!  Thank you for contributing your genetic material.

    Hm, how many limbs do you have?  And do you like to wander around the African veldt?  And how big is your forehead?  I only ask because you remind me of someone I used to work for.

    vc


    You're trying too hard.

    Sincerely,

    Richard Nixon
  • voodooc (cs) in reply to Richard Nixon
    Richard Nixon:
    voodooc:

    It's an Idiot Orgy!  Thank you for contributing your genetic material.

    Hm, how many limbs do you have?  And do you like to wander around the African veldt?  And how big is your forehead?  I only ask because you remind me of someone I used to work for.

    vc


    You're trying too hard.

    Sincerely,

    Richard Nixon


    "I apologize for the length of this insult, but I didn't have time to make it shorter."

    vc
  • Gene Wirchenko (cs) in reply to hank miller
    hank miller:
    Welcome to the club.   The rest of us have been seen the same problems.

    There is good reason there is no preview button - anything previewed NEVER showed up the same when posted, while if you didn't preview (just trusting to the devil) once in a while things look like you want them to.


    It worked fine for me.  I did not ever try HTML though, and switching between that and Design apparently did cause trouble.

    Sincerely,

    Gene Wirchenko

  • Maurits (cs) in reply to Joost_
    Joost_:
    <span style="font-family: courier new;">Pfft. I used to work at Lockheed where we would use lookup tables to avoid calculation of modulo. </span>

    <span style="font-family: courier new;">Vector generateModuloLookup(int table, int max) {</span>
    <span style="font-family: courier new;">&nbsp; Vector lookup = new Vector();<br> </span><span style="font-family: courier new;">&nbsp; for(int i = 0; i &lt; max; i++)<br> &nbsp; {<br> &nbsp;&nbsp;&nbsp; Integer value = new Integer(i * table);<br style="font-family: courier new;"> </span><span style="font-family: courier new;"></span><span style="font-family: courier new;">&nbsp;&nbsp;&nbsp; lookup.Add(value);<br> &nbsp; }<br> &nbsp; return lookup;<br style="font-family: courier new;"> </span><span style="font-family: courier new;"></span><span style="font-family: courier new;">}<br> <br> int lookupModule(Vector lookup, Integer number)<br> {<br> &nbsp; </span><span style="font-family: courier new;">return lookup.indexOf(number);</span>
    <span style="font-family: courier new;"><br> int lookupModulo(Vector lookup, int number)<br> {<br> &nbsp; return lookupModulo(new Integer(number));<br> }<br> </span>


    Lookup tables I can understand.  But surely generating them at compile time is better than generating them at run time!
  • waynerad (cs)

    Everyone is commenting on the modulo. But what about the gazillion time classes that all invoke each other's constructors and do time conversions just to store a single date/time??? That's the real crazy part man.

  • Quinnum (cs) in reply to trollable
    trollable:
    My Sun5 is unplugged and i don't remember if the 68000 supports neither the modulo instruction nor the div one. A possible guess is the pasted code may run faster on the old Solaris/68000 combination. The fact it is C++and/or Solaris doesn't really matter, the CPU does.



    The 68K had the DIV instruction which resulted in the quotient and the remainder in one (slightly annoying) package.

    e.g. <span style="font-family: courier new; font-weight: bold;">DIV D0,D1</span>

    would divide the full 32 bit value of D1 by the lower 16 bits of D0, resulting in the quotient being in the lower 16 bits and the remainder in the upper 16 bits of D1. Which was a pain in the arse if the quotient was greater than a 16 bit result, like trying to divide 2^31 by 10 for example.

    Still - 68K assembly was a joy to program back in the heady Amiga days, unlike the shitty x86 and it's crappy instruction set and segments. bleh...

  • RC (unregistered)

    NAME
           div, ldiv, lldiv, imaxdiv - compute quotient and remainder of an integer division

    SYNOPSIS
           #include <stdlib.h>

           div_t div(int numerator, int denominator);
           ldiv_t ldiv(long numerator, long denominator);
           lldiv_t lldiv(long long numerator, long long denominator);

           #include <inttypes.h>

           imaxdiv_t imaxdiv(intmax_t numerator, intmax_t denominator);

    DESCRIPTION
           The  div()  function computes the value numerator/denominator and returns the quotient and
           remainder in a structure named div_t that contains two  integer  members  (in  unspecified
           order)  named  quot  and rem.  The quotient is rounded towards zero.  The result satisfies
           quot*denominator+rem = numerator.

           The ldiv() and lldiv() and imaxdiv() functions do the same, dividing numbers of the  indi-
           cated  type  and  returning  the result in a structure of the indicated name, in all cases
           with fields quot and rem of the same type as the function arguments.

    RETURN VALUE
           The div_t (etc.) structure.

    EXAMPLE
           After
                   div_t q = div(-5, 3);
           the values q.quot and q.rem are -1 and -2, respectively.

    CONFORMING TO
           SVID 3, BSD 4.3, ISO 9899.  The functions lldiv() and imaxdiv() were added in ISO C99.

    SEE ALSO
           abs(3), remainder(3)

  • anrieff (unregistered)

    The loop in the WTF is actually faster than the modulo operator, even on the IA32, if the value is less than eight times the divisor. So, before considering this as a true WTF we must know the divisor.

  • Just (cs) in reply to Just
    Just:

    I could have sworn that C++ only allows for one implicit conversion, not 3 as described in the WTF. Is my memory failing, or is this a Solaris compiler extension (highly unlikely), or is the WTF submitter mistaken?

    Anyone know the answer to this? It's really bugging me now.

  • Andreas (unregistered)

    Our company once had the (dubious) pleasure to further develop a product from a company we bought. I wasn't actively involved with that (fortunately) but the story goes that in the code a similar function (as FindTheRemainder()) was found, only after it the following "computation" was performed:

    <font face="Courier New"><pre>int real_reminder = 0; while(remainder &gt; 0) { &nbsp;&nbsp;&nbsp;real_reminder++; &nbsp;&nbsp;&nbsp;remainder--; }</pre></font>
  • aniefer (unregistered) in reply to Just
    Just:
    Just:

    I could have sworn that C++ only allows for one implicit conversion, not 3 as described in the WTF. Is my memory failing, or is this a Solaris compiler extension (highly unlikely), or is the WTF submitter mistaken?

    Anyone know the answer to this? It's really bugging me now.



    Without taking too long to consider whether or not I'm forgetting something, from the C++ spec:
    section 12.3:  "At most one user-defined conversion (constructor of conversion function) is implicitly applied to a single value."

    section 13.3.3.1.2:  during function resolution, a user-defined conversion sequence consists of an initial standard conversion , followed by a user-defined conversion, followed by a second standard conversion sequence.
  • Foo (unregistered) in reply to voodooc

    And you try ta tell that to the kids these days and they won't believe you!

    (for those who the joke completely misses, listen/watch the Four Yorkshiremen sketch by Monty Python) (as if people who haven't seen it deserve to be called programmers or something...)

Leave a comment on “Library.Math.Functions.3rdGrade.FindTheRemainder()”

Log In or post as a guest

Replying to comment #:

« Return to Article