Arithmetic
Arithmetic
ARITHMETIC
2
ARITHMETIC…1
?- X=1+2.
Prolog will answer
X=1+2. not X=3.
The is operator
X is 1+2.
The answer will be
X=3.
3
ARITHMETIC…
Comparison operator
X>Y…………. X is grater than Y
X<Y………… X is less than Y
X>=Y………. X is grater than or equal to Y
X=<Y ………. X is less than or equal to Y
X=:=Y………. The value of X and Y are equal
X=\=Y--------- The value of X and Y are not equal
Note:
X=Y matches object X and object Y
Example: 1+2=1+2……true
1+2=2+1…. False
X=:= Y …..arithmetic evaluation
Example: 1+2=:=1+2….. True 4
1+2=:=2+1 …… True
EXERCISE
Define the relation
max(X,Y,Max). So that Max is the greater of two number X
and Y.
Write a prolog program that can use to check factorial of
a number?
For example
?- fact(3,6).
True
?- fact(3,7).
Some error message
max(X,Y):-X>Y,Max is X, write(Max).
max(X,Y):-X<Y,Max is Y, write(Max).
6
fact(0,1).
fact(X,Y):- K is X-1, fact(K,M), Y is X*M.
7
Ho
wt
wo he r
rks ec
for ursi
nu fa c
ve
r
mb toria elati
er. l o on
fa
8
inbetween(2,5,X)
How the recursive
relation works for
Second rule X=K
inbetween relation
J1 is 3 , inbetween (2,3,K)
First rule X=J=4
First rule X=J= 4
Second rule X=K
J1 is 2 , inbetween (2,3,K)
First rule X=J= 3
Second rule
X=K
Fail
First rule X=J= 2 9
go:-write('what do you wish to do \n type 1--for addition \n 2--- for
subtraction \n 3-- multiplication \n 4--for division \n '),
read(A),(A=:=1->write("input numbers to
add"),read(X),read(Y),R is X+Y,write(X+Y=R);(A=:=2-
>write("input numbers to subtract"),read(X),read(Y),R is X-
Y,write(X-Y=R);(A=:=3->write("input numbers to
multiply"),read(X),read(Y),R is X*Y,write(X*Y=R);(A=:=4-
>write("input numbers to divide"),read(X),read(Y),(Y=:=0-
>write("Y can't be 0"),fail), R is
X/Y,write(X/Y=R);write("invalid"))))).
10