Hi does anyone know other implementation to compute X at power N in Prolog beside this one:
predicates
power(real, integer, real)
clauses
power(_,0,1).
power(X,N,R):-
N<0,
N1 = -N,
X1 = 1/X,
power(X1,N1,R).
power(X,N,R):-
N1=N-1,
power(X,N1,R1),
R=R1*X.
In any case, I would treat the negative exponent with a predicate, as already given in the problem post, which is:
So the following assume non-negative exponents.
This algorithm multiples the base
N
times:This algorithm multiples the base
N
times using tail recursion:This version uses the "power of 2" method, minimizing the multiplications:
This version uses a "power of 2" method, minimizing multiplications, but is tail recursive. It's a little different than the one Boris linked: