integer_division

Integer Division provides a set of integral division and remainder procedures.

The library is based on Scheme's SRFI 141, and provides the same six integer division operations, albeit with a different API.

There are six kinds of division supported: floor, ceiling, truncate, round, Euclidean and balanced. Each is supported by one procedure, which returns a `divide_result` instance containing the quotient and remainder.

It is an error if both parameters are not integers, or the denominator is zero.

Links

Procedures

divide_balanced (numerator, denominator)

Balances the remainder to ensure:

-|d/2| <= r < |d/2|

For example:

  divide_balanced(7,3).quotient => 2
  divide_balanced(7,3).remainder => 1
  divide_balanced(8,3).quotient => 3
  divide_balanced(8,3).remainder => -1
  divide_balanced(9,3).quotient => 3
  divide_balanced(9,3).remainder => 0
  divide_balanced(10,3).quotient => 3
  divide_balanced(10,3).remainder => 1

Parameters:

numerator
integer valued dividend
denominator
integer valued, non-zero divisor

divide_ceiling (numerator, denominator)

Returns q = ceiling(n/d), r = n - q.d

For example:

  divide_ceiling(7,3).quotient => 3
  divide_ceiling(7,3).remainder => -2
  divide_ceiling(-7,2).quotient => -3
  divide_ceiling(-7,2).remainder => -1

Parameters:

numerator
integer valued dividend
denominator
integer valued, non-zero divisor

divide_euclidean (numerator, denominator)

If denominator > 0 returns divide_floor, else returns divide_ceiling.

This ensures 0 <= r < |d|

For example:

  divide_euclidean(7,3).quotient => 2
  divide_euclidean(7,3).remainder => 1
  divide_euclidean(-7,3).quotient => -3
  divide_euclidean(-7,3).remainder => 2
  divide_euclidean(7,-3).quotient => -2
  divide_euclidean(7,-3).remainder => 1

Parameters:

numerator
integer valued dividend
denominator
integer valued, non-zero divisor

divide_floor (numerator, denominator)

Returns q = floor(n/d), r = n - q.d

For example:

  divide_floor(7,3).quotient => 2
  divide_floor(7,3).remainder => 1
  divide_floor(-7,2).quotient => -4
  divide_floor(-7,2).remainder => 1

Parameters:

numerator
integer valued dividend
denominator
integer valued, non-zero divisor

divide_round (numerator, denominator)

Returns q = round(n/d), r = n - q.d

For example:

  divide_round(7,3).quotient => 2
  divide_round(7,3).remainder => 1
  divide_round(-7,2).quotient => -4
  divide_round(-7,2).remainder => 1

Parameters:

numerator
integer valued dividend
denominator
integer valued, non-zero divisor

divide_truncate (numerator, denominator)

Returns q = maths_truncate(n/d), r = n - q.d

For example:

  divide_truncate(7,3).quotient => 2
  divide_truncate(7,3).remainder => 1
  divide_truncate(-7,2).quotient => -3
  divide_truncate(-7,2).remainder => -1

Parameters:

numerator
integer valued dividend
denominator
integer valued, non-zero divisor

Records

divide_result (quotient, remainder)

Holds the quotient and remainder result of a divide operation.


Home