Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 290
dtech Avatar asked Nov 29 '11 21:11

dtech


People also ask

How do you find the quotient and the remainder?

When we divide A by B in long division, Q is the quotient and R is the remainder.

How do you use a division algorithm to find the quotient and remainder?

When we divide a positive integer (the dividend) by another positive integer (the divisor), we obtain a quotient. We multiply the quotient to the divisor, and subtract the product from the dividend to obtain the remainder. Such a division produces two results: a quotient and a remainder.

How do you find the quotient and remainder in C#?

The Math. DivRem() method in C# is used to divide and calculate the quotient of two numbers and also returns the remainder in an output parameter.

Which command is used to find out the quotient of two numbers?

Quotient = Dividend ÷ Divisor. Let us solve 435 ÷ 4. Here, 435 is the dividend and 4 is the divisor.


2 Answers

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.

like image 75
John Dibling Avatar answered Sep 30 '22 15:09

John Dibling


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

like image 36
Greg Hewgill Avatar answered Sep 30 '22 15:09

Greg Hewgill