Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use recursion to sum/add the number between x and y?

I would like to ask as to how would you be able to make a recursion that would add from your starting number (x) up to the end (y).

E.G. = summation(Ans, 1, 5). Ans = 15

(1+2+3+4+5) = 15 //is what should occur in the recursion

So far what I've done is this:

sumFrom(Sum, X ,Y) :- X>Y, !, write('Start should not be greater than End').
sumFrom(Sum, X ,Y) :- Sum is X+Y,
        Next is X+1,
        sumFrom(Sum, Next, Y).

I am still new to prolog so please be gentle.

like image 581
Fight or flight Avatar asked Dec 15 '25 07:12

Fight or flight


1 Answers

Since pure (the declarative subset of) Prolog doesn't have loops and mutable variables, performing arithmetic can be tricky. I think it's worth to learn about libraries, when the basic has become clear:

?- aggregate(sum(N),between(1,5,N),S).
S = 15.
like image 156
CapelliC Avatar answered Dec 16 '25 21:12

CapelliC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!