In: Computer Science
Activity 6. Write a Prolog definition of the greatest common divisor of two numbers. Then use it to compute gcd(4, 10), gcd(15, 36), and gcd(25, 55).
Activity 7. Write a Prolog program to find the last item in a list.
give me the screenshot pls
Activity 6:- Prolog definition of the greatest common divisor of two numbers.
gcd = greatest common divisor
The predicate =/2 is for unification, not arithmetic assignment
The expression X1 = X-Y doesn't subract Y from X and store the result in X1.Rather , it unifies X1 with the term ,(X,Y). If for example, X= 5and Y=3 , then the result would be, X1 = 5-3 , not X1 = 2. The solution is to use is /2 which assigns evaluated arithmetic expressions: X1 is X-Y.
Other predicates, besides the base case predicate, successfully match the base case
The clause , gcd(0,X,X):- X>0 is a reasonable base case, but it is never attempted because the second clause(gcd(X,Y,Z):-X<Y,...) will always successfully match the same conditions first, leading to infinite recursion and a stack overflow.
One way to fix this is to move the base case to the first clause and use a cut to avoid backtracking after it successfully executes:
gcd(0, X, X):- X>0,!.
gcd(X,Y,Z):- X>= Y, X1 is X- Y, gcd(X1 , Y, Z).
gcd(X, Y, Z):- X<Y, X1 is Y - X , gcd(X1, X, Z).
Now,
gcd(4, 10, X).
X = 2?;
2. gcd(15, 36)
gcd(15 , 36 , X).
X = 3?;
3.gcd(25, 55)
gcd(25, 55, X).
X = 5?;
Activity 7:- Prolog Program to find the last item in a list