Prolog/Math.pro

31 lines
715 B
Prolog
Raw Normal View History

% Compute the nth number in the fibonacci sequence
fib(0, 0).
fib(1, 1).
fib(X, Res):-
X1 is X - 1,
X2 is X - 2,
fib(X1, Tmp1),
fib(X2, Tmp2),
Res is Tmp1 + Tmp2.
% Compute the nth element of the integer factorial
fac(0, 1).
fac(X, Res):-
X1 is X - 1,
fac(X1, Tmp),
Res is Tmp * X.
% Sums all integer numbers between and inclusive X and inclusive Y and writes the result to Res.
%
% example: sum(0, 9, X).
% output: X = 45
% explanation: 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 9
sum(X, X, X).
sum(X, Y, Res):-
X < Y,
X1 is X + 1,
sum(X1, Y, Tmp),
Res is Tmp + X.
sum(X, Y, Res):- % if X is bigger than Y, swap the operands and call sum again
X > Y,
sum(Y, X, Res).