嗨,有谁知道在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.
无论如何,我会用谓词处理负指数,正如问题帖子中已经给出的那样,即:
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).