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?
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?
代码有两个问题。
这是固定代码:
pow(_,0,1).
pow(B,E,R) :- E > 0,!, E1 is E -1, pow(B,E1,R1), R is B * R1.
这是使用累加器的第二个尾递归版本
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).
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.