Artificial Intelligence Lab
Artificial Intelligence Lab
PART 1
factorial(0, 1).
factorial(N, M) :- N > 0,
Prev is N -1,
factorial(Prev, M1),
M is M1 * N.
gcd(X,0):- write(X).
gcd(X,Y):-
M is mod(X,Y),
gcd(Y,M).
1|Page
Artificial Intelligence Lab
fib(0,0).
fib(1,1).
fib(F,N) :-
N>1,
N1 is N-1,
N2 is N-2,
fib(F1,N1),
fib(F2,N2),
F is F1+F2.
count(0,[]).
count(N,[_|TAIL]) :-
count(N1,TAIL),
N is N1+1.
2|Page
Artificial Intelligence Lab
gcdList(X,[],X).
gcdList(X,[Y|TAIL],R) :-
gcd(X,Y,Z),
gcdList(Z,TAIL,R).
find_gcd(X,[A,B|TAIL]):-
gcd(A,B,R),
gcdList(R,TAIL,X).
3|Page
Artificial Intelligence Lab
10) Write a program in PROLOG to check whether a number or string is a palindrome or not
insert_end(X,[],[X]).
insert_end(X,[Y|TAIL],[Y|R]) :-
insert_end(X,TAIL,R).
revList([],[]).
revList([Y|TAIL],Z) :-
revList(TAIL,R),
insert_end(Y,R,Z).
palin(X):- revList(X,X),write('Palindrome').
12) Write a program in PROLOG for linear search/ binary search in a list
linSearch(X,[X|TAIL],1).
linSearch(X,[Y|TAIL],POS):-
linSearch(X,TAIL,P),
POS is P+1.
13) Write a program in PROLOG to sort n numbers using the bubble sort algorithm .
bubble_sort(List,Sorted):-b_sort(List,[],Sorted).
b_sort([],Acc,Acc).
b_sort([H|T],Acc,Sorted):-bubble(H,T,NT,Max),b_sort(NT,[Max|Acc],Sorted).
bubble(X,[],[],X).
bubble(X,[Y|T],[Y|NT],Max):-X>Y,bubble(X,T,NT,Max).
bubble(X,[Y|T],[X|NT],Max):-X=<Y,bubble(Y,T,NT,Max).
4|Page
Artificial Intelligence Lab
5|Page
Artificial Intelligence Lab
PART 2
6. Write a Prolog Program to find the square root of a number using function.
sqRoot(X,R):- R is sqrt(X).
7. Write a Prolog Program to find the modulus of two numbers using function.
modulus(X,Y):-A is mod(X,Y),write(A).
6|Page
Artificial Intelligence Lab
11. Write a Prolog Program to print N to 20 using for loop (Fixing the end value).
fun(20):-write(20).
fun(N):-N < 20,
write(N),write(', '),
N1 is N+1,
fun(N1).
12. Write a Prolog Program to print N to 20 numbers using for loop, in reverse order.
fun(20):-write(20).
fun(N):-N > 20,
write(N),write(', '),
N1 is N-1,
fun(N1).
7|Page
Artificial Intelligence Lab
20. Write a Lisp program to find whether a number is positive or negative or zero.
(setq a (read))
(cond
( (> a 0) (format t "~d is positive" a) )
( (< a 0)(format t "~d is negative" a) )
(t (format t "~d is zero" a))
)
8|Page