Reputation: 63
Exactly what's the Prolog definition for power function. I wrote this code and it give some errors I wanna know exact code for the power function.
pow(X,0,1).
pow(X,Y,Z):-Y1=Y-1,pow(X,Y1,Z1),Z1=Z*X.
Anything wrong with this code?
Upvotes: 0
Views: 9156
Reputation: 1085
There are two problems with the code.
Here is the fixed code:
pow(_,0,1).
pow(B,E,R) :- E > 0,!, E1 is E -1, pow(B,E1,R1), R is B * R1.
Here is a second, tail recursive version using an accumulator
powa(B,E,R) :- powa(B,E,1,R).
powa(_,0,A,A).
powa(B,E,A,R) :- E > 0, !, E1 is E - 1, A1 is B * A, powa(B,E1,A1,R).
Upvotes: 2
Reputation: 56665
Have a look here - power function in prolog. The built-in pow predicate is not implemented in prolog for efficiency reason - as most arithmetic predicates.
Upvotes: 1