0

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?

4

2 回答 2

2

代码有两个问题。

  • 要在 prolog 中进行算术运算,您必须使用 is/2 而不是 =
  • 必须交换乘法中的变量(Z 是 Z1*X)
  • 您应该设置一个保护以确保指数为正,否则您可能会遇到程序不会终止的情况

这是固定代码:

  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).
于 2011-09-27T05:06:05.673 回答
1

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.

于 2010-04-17T15:50:30.067 回答