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

22,394

Solution 1

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.

Solution 2

Yes, there is a standard function called div() (and ldiv, and maybe even lldiv) that does this.

Share:
22,394
dtech
Author by

dtech

Updated on July 09, 2022

Comments

  • dtech
    dtech over 1 year

    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?

  • John Dibling
    John Dibling over 12 years
    @ddriver: Yes, but see my edit.
  • dtech
    dtech over 12 years
    yes, thank you very much for the detailed response
  • Mike Steinert
    Mike Steinert over 12 years
    FYI - The GLIBC implementation of div simply does a divide and a modulo, so you aren't gaining anything. Actually, what you gain is the function call overhead.
  • caf
    caf over 12 years
    @MikeSteinert: That depends on your architecture - eg glibc has an assembly implementation of div for Alpha