ldiv() – lldiv() — Perform Long and Long Long Division
Format (ldiv()
)
#include <stdlib.h>
ldiv_t ldiv(long int numerator, long int denominator);
Format (lldiv()
)
#include <stdlib.h>
lldiv_t lldiv(long long int numerator, long long int denominator);
Language Level
ANSI
Threadsafe
Yes
However, only the function version is threadsafe. The macro version is NOT threadsafe.
Description
The ldiv()
function
calculates the quotient and remainder of the division of numerator by denominator.
Return Value
The ldiv()
function
returns a structure of type ldiv_t, containing both the quotient
(long int quot) and the remainder (long int rem).
If the value cannot be represented, the return value is undefined.
If denominator is 0, an exception
is raised.
The lldiv()
function computes the quotient
and remainder of the numerator parameter
by the denominator parameter.
The
lldiv()
function returns a structure
of type lldiv_t, containing both the quotient and the remainder. The
structure is defined as: struct lldiv_t
{
long long int quot; /* quotient */
long long int rem; /* remainder */
};
If the division is inexact, the sign of the resulting
quotient is that of the algebraic quotient, and magnitude of the resulting
quotient is the largest long long integer less than the magnitude
of the algebraic quotient. If the result cannot be represented (for
example, if the denominator is 0),
the behavior is undefined.Example
This example uses
ldiv()
to calculate
the quotients and remainders for a set of two dividends and two divisors.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long int num[2] = {45,-45};
long int den[2] = {7,-7};
ldiv_t ans; /* ldiv_t is a struct type containing two long ints:
'quot' stores quotient; 'rem' stores remainder */
short i,j;
printf("Results of long division:\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
{
ans = ldiv(num[i], den[j]);
printf("Dividend: %6ld Divisor: %6ld", num[i], den[j]);
printf(" Quotient: %6ld Remainder: %6ld\n", ans.quot, ans.rem);
}
}
/******************** Expected output: **************************
Results of long division:
Dividend: 45 Divisor: 7 Quotient: 6 Remainder: 3
Dividend: 45 Divisor: -7 Quotient: -6 Remainder: 3
Dividend: -45 Divisor: 7 Quotient: -6 Remainder: -3
Dividend: -45 Divisor: -7 Quotient: 6 Remainder: -3
*/