added file containing predicates for various math functions

This commit is contained in:
Sven Vogel 2023-06-12 15:19:03 +00:00
parent 7f72f62df7
commit 4d1c3d9ab2
1 changed files with 31 additions and 0 deletions

31
Math.pro Normal file
View File

@ -0,0 +1,31 @@
% 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).