c++cmodulointeger-division

How can I get the quotient and the remainder in a single step?


Possible Duplicate:
Divide and Get Remainder at the same time?

Is it possible to get both the quotient and the remainder of integer division in a single step, i.e., without performing integer division twice?


Solution

  • div will do this. See reference and example:

    /* div example */
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ()
    {
      div_t divresult;
      divresult = div (38,5);
      printf ("38 div 5 => %d, remainder %d.\n", divresult.quot, divresult.rem);
      return 0;
    }
    

    Output:

    38 div 5 => 7, remainder 3.
    

    EDIT:

    The C Specification says:

    7.20 General utilities

    The types declared are size_t and wchar_t (both described in 7.17),
    div_t
    which is a structure type that is the type of the value returned by the div function,
    ldiv_t
    which is a structure type that is the type of the value returned by the ldiv function, and
    lldiv_t
    which is a structure type that is the type of the value returned by the lldiv function.
    

    ... but it doesn't say what the definition of div_t is.