4.27.1 Special purpose integer arithmetic
The predicates in this section provide more logical operations between integers. They are not covered by the ISO standard, although they are `part of the community' and found as either library or built-in in many other Prolog systems.
- between(+Low, +High, ?Value)
- Low and High are integers, High >=Low.
If
Value is an integer, Low =<Value
=<High. When Value is a variable it is
successively bound to all integers between Low and High.
If High is
inf
orinfinite
105We preferinfinite
, but some other Prolog systems already useinf
for infinity; we accept both for the time being. between/3 is true iff Value >=Low, a feature that is particularly interesting for generating integers from a certain value. - succ(?Int1, ?Int2)
- True if Int2 = Int1 + 1 and Int1
>= 0. At least one of the arguments must be instantiated to a
natural number. This predicate raises the domain error
not_less_than_zero
if called with a negative integer. E.g.succ(X, 0)
fails silently andsucc(X, -1)
raises a domain error.106The behaviour to deal with natural numbers only was defined by Richard O'Keefe to support the common count-down-to-zero in a natural way. Up to 5.1.8, succ/2 also accepted negative integers. - plus(?Int1, ?Int2, ?Int3)
- True if Int3 = Int1 + Int2. At least two of the three arguments must be instantiated to integers.
- divmod(+Dividend, +Divisor, -Quotient, -Remainder)
- This predicate is a shorthand for computing both the Quotient
and
Remainder of two integers in a single operation. This allows
for exploiting the fact that the low level implementation for computing
the quotient also produces the remainder. Timing confirms that this
predicate is almost twice as fast as performing the steps independently.
Semantically, divmod/4
is defined as below.
divmod(Dividend, Divisor, Quotient, Remainder) :- Quotient is Dividend div Divisor, Remainder is Dividend mod Divisor.
Note that this predicate is only available if SWI-Prolog is compiled with unbounded integer support. This is the case for all packaged versions.
- nth_integer_root_and_remainder(+N, +I, -Root, -Remainder)
- True when Root ** N + Remainder = I. N and I
must be integers.107This predicate
was suggested by Markus Triska. The final name and argument order is by
Richard O'Keefe. The decision to include the remainder is by Jan
Wielemaker. Including the remainder makes this predicate about twice as
slow if Root is not exact.
N must be one or more. If I is negative and
N is odd, Root and Remainder
are negative, i.e., the following holds for I < 0:
% I < 0, % N mod 2 =\= 0, nth_integer_root_and_remainder( N, I, Root, Remainder), IPos is -I, nth_integer_root_and_remainder( N, IPos, RootPos, RemainderPos), Root =:= -RootPos, Remainder =:= -RemainderPos.