在Prolog中执行x at power n的其他实现

时间:2014-01-10 10:31:54

标签: prolog turbo-prolog

嗨,有没有人知道在Prolog旁边以权力N计算X的其他实现:

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.

1 个答案:

答案 0 :(得分:1)

在任何情况下,我都会用谓词来处理负指数,如问题帖子中所给出的那样:

power(Base, N, P) :-
    N < 0,
    N1 is -N,
    power(Base, N1, P1),
    P is 1/P1.

以下假设非负指数。

此算法将基数N倍乘以:

power1(Base, N, P) :-
    N > 0,
    N1 is N - 1,
    power1(Base, N1, P1),
    P is P1 * Base.
power1(Base, N, P) :-
    N < 0,
    N1 is N + 1,
    power1(Base, N1, P1),
    P is P1 / Base.
power1( _Base, 0, 1 ).

此算法使用尾递归将基数N倍增:

power1t(Base, N, P) :-
    N >= 0,
    power1t(Base, N, 1, P).
power1t(Base, N, A, P) :-
    N > 0,
    A1 is A * Base,
    N1 is N - 1,
    power1t(Base, N1, A1, P).
power1t(_, 0, P, P).

此版本使用“2的幂”方法,最小化乘法:

power2(_, 0, 1).
power2(Base, N, P) :-
    N > 0,
    N1 is N div 2,
    power2(Base, N1, P1),
    (   0 is N /\ 1
    ->  P is P1 * P1
    ;   P is P1 * P1 * Base
    ).

此版本使用“2的幂”方法,最小化乘法,但尾递归。这与鲍里斯的联系有点不同:

power2t(Base, N, P) :-
    N >= 0,
    power2t(Base, N, Base, 1, P).
power2t(Base, N, B, A, P) :-
    N > 0,
    (  1 is N /\ 1
    -> A1 is B * A
    ;  A1 = A
    ),
    N1 is N div 2,
    B1 is B * B,
    power2t(Base, N1, B1, A1, P).
power2t(_, 0, _, P, P).