I'm working on a homework assignment, consisting of 2 parts. The first is to write a Prolog program that checks if a certain pair X, Y belongs to a http://en.wikipedia.org/wiki/Triangular_number. For example: (2, 3) = true; (4, 10) = true et cetera.
The first solution uses 'ordinary' recursion, and I've solved this like this:
triangle(0, 0).
triangle(X, Y) :- X > 0, Y > 0, A is X - 1, B is Y - X, triangle(A, B).
The second part is to solve this using tail recursion/an accumulator, using a triangle/3 predicate. Though I have used an accumulator in another assigment, in which the use was quite obvious, so I have a general idea of how to use an accumulator, I'm quite puzzeled as to how to use it in this context.
So, I'm not looking for an algorithm, I'd much rather solve that myself, but more of a practical advise on how to apply an accumulator in this context.
The beginning is always the same, i.e. the first three lines are basically what you write for each and every tail recursive predicate (with a
[]
instead of a0
for list predicates).From there you can go on without many changes:
Here are some statistics for large X:
So, while your own predicate is basically already tail recursive (because the recursive call is the last thing to do) the version with an accumulator still saves some time because you do not need the check for
Y > 0
. If you introduce this line in thetriangle_t
predicate, they have exactly the same runtime characteristics again:Also note that you can now use the predicate to generate the n'th triangular number.