I\'m trying to create a program in Prolog which takes two numbers - A and B and finds the sum of the numbers from A to B, including them.
To sum up: sum(1, 5, C) should
I suppose you could use brute force to compute the sum of a finite arithmetic sequence, but wouldn't it be easier just to use your maths?
sum(A,B,X) :-
A =< B ,
N is 1+B-A ,
X is N*(A+B) / 2
.
Or, more generally, for computing the sum of a finite sequence of n terms, starting with a, with a "step size" (relative difference) of d, you get:
sum(A,D,N,S) :- S is (N*(2*A+(N-1)*D))/2 .
But if you're going to use brute force, make it tail recursive:
sum(A,B,S) :- A =< B , sum(A,B,0,S) .
sum(A,B,S,S) :-
A > B
.
sum(A,B,T,S) :-
A =< B ,
T1 is T+A ,
A1 is A+1 ,
sum(A1,B,T1,S)
.