projog

2.4. Prolog Arithmetic Operators

Prolog can be used to perform arithmetic. Prolog supports the common arithmetic operators:

Arithmetic expressions can be used as the right-hand argument of the is operator to assign the result of the expression to a variable. Arithmetic expressions will also be evaluated if used as arguments for the numeric comparison operators: =:=, =\=, <, =<, > and >=.

Examples

?- X is 45345.
X = 45345

yes

?- X is -876878.
X = -876878

yes

?- X is 2+1.
X = 3

yes

?- X is 12-5.
X = 7

yes

?- X is 6*7.
X = 42

yes

?- X is 6/2.
X = 3

yes

?- X is 6//2.
X = 3

yes

?- X is 7/2.
X = 3.5

yes

?- X is 7//2.
X = 3

yes

?- X is 7 * 4 // 2.
X = 14

yes

?- X is 5 mod 3.
X = 2

yes

?- X is 2147483647 + 1.
X = 2147483648

yes

?- X is -2147483648 - 1.
X = -2147483649

yes

The maximum integer value that can be represented is 9223372036854775807

?- X is 9223372036854775807.
X = 9223372036854775807

yes

?- X is 9223372036854775806 + 1.
X = 9223372036854775807

yes

?- X is 9223372036854775806 + 2.
X = -9223372036854775808

yes

The minimum integer value that can be represented is -9223372036854775808

?- X is -9223372036854775808.
X = -9223372036854775808

yes

?- X is -9223372036854775807 - 1.
X = -9223372036854775808

yes

?- X is -9223372036854775807 - 2.
X = 9223372036854775807

yes

Prolog evaluates numerical expressions using the BODMAS rule to determine the order in which operations are performed.

?- X is 1+2*3.
X = 7

yes

?- X is 2*3+1.
X = 7

yes

?- X is (1+2)*3.
X = 9

yes

?- X is 2*(3+1).
X = 8

yes

?- X is -(4+6).
X = -10

yes

Variables must be instantiated to numerical terms before they can be used in calculations.

?- X is 1 + Y.

Cannot get Numeric for term: Y of type: VARIABLE

?- Y = 4, X is 1 + Y.
X = 5
Y = 4

yes

?- Y = 6-2, X is 1 + Y.
X = 5
Y = 6 - 2

yes

?- Y = 2*4, X is -Y.
X = -8
Y = 2 * 4

yes

Examples of using decimal point numbers in calculations.

?- X is 1.3 + 1.2.
X = 2.5

yes

?- X is 1.3 + 1.
X = 2.3

yes

?- X is 1 + 1.2.
X = 2.2

yes

?- X is 3.5 - 1.25.
X = 2.25

yes

?- X is 3.5 - 1.
X = 2.5

yes

?- X is 3 - 1.25.
X = 1.75

yes

?- X is -9.6.
X = -9.6

yes

?- Y = 9.6, X is -Y.
X = -9.6
Y = 9.6

yes

?- X is 6.3 * 2.75.
X = 17.325

yes

?- X is 6.3 * 2.
X = 12.6

yes

?- X is 6 * 2.75.
X = 16.5

yes

?- X is 8.5 / 2.5.
X = 3.4

yes

?- X is 8.5 / 2.
X = 4.25

yes

?- X is 8 / 2.5.
X = 3.2

yes

?- X is 5 mod 2.
X = 1

yes

?- X is 5 mod -2.
X = -1

yes

?- X is -5 mod -2.
X = -1

yes

?- X is -5 mod 2.
X = 1

yes

?- X is 5 rem 2.
X = 1

yes

?- X is 5 rem -2.
X = 1

yes

?- X is -5 rem -2.
X = -1

yes

?- X is -5 rem 2.
X = -1

yes

?- X is 2 mod -5.
X = -3

yes

?- X is 2 rem -5.
X = 2

yes