1

嗨,除了这个之外,有谁知道在 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.
4

1 回答 1

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).
于 2014-01-10T14:43:13.353 回答