C library - ldiv() function



The C stdlib library ldiv() function is used to divide long numerator by long denominator. It then return the long integral quotient and remainder.

For example, pass the long numerator 100000L and long denominator 30000L to the ldiv() function in order to obtain the result. Find the quotient by evaluating the 'result.quot' (100000L/30000L = 3) and the remainder by evaluating 'result.rem '(100000L%30000L = 10000).

Syntax

Following is the C library syntax of the ldiv() function −

ldiv_t ldiv(long int numer, long int denom)

Parameters

This function accepts the following parameters −

  • numer − It represents a long numerator.

  • denom − It represents a long denominator.

Return Value

This function returns the value in a structure defined in <cstdlib> with two members: long int 'quot' and long int 'rem'.

Example 1

In this example, we create a basic c program to demonstrate the use of ldiv() function.

#include <stdio.h>
#include <stdlib.h>

int main () {
   ldiv_t res;

   res = ldiv(100000L, 30000L);

   printf("Quotient = %ld\n", res.quot);

   printf("Remainder = %ld\n", res.rem);
   
   return(0);
}

Output

Following is the output −

Quotient = 3
Remainder = 10000

Example 2

This is another example, we are passing both numerator and denominator as a negative long integer to the ldiv() function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
   long int numerator = -100520;
   long int denominator = -50000;
   
   // use div function	
   ldiv_t res = ldiv(numerator, denominator);
   
   printf("Quotient of 100/8 = %ld\n", res.quot);
   printf("Remainder of 100/8 = %ld\n", res.rem);
   
   return 0;
}

Output

Following is the output −

Quotient of 100/8 = 2
Remainder of 100/8 = -520

Example 3

Below c program calculates the quotient and remainder when dividing two long integers.

#include <stdio.h>
#include <stdlib.h>

int main() {
   // use ldiv() function
   ldiv_t res = ldiv(50, 17);
   // Display the quotient and remainder
   printf("ldiv(50, 17) gives quotient = %ld and remainder = %ld\n", res.quot, res.rem);
   return 0;
}

Output

Following is the output −

ldiv(50, 17) gives quotient = 2 and remainder = 16
Advertisements