2 回答

TA貢獻1853條經驗 獲得超9個贊
這是您以邏輯上純凈的方式找到“二的冪”的方法!
使用sicstus-prolog 4.3.5 library(reif)和library(clpz):
:-use_module([ library(reif),library(clpz) ])。
power_of_two_t(I,T):-
L#=分鐘(I,1),
M#= I / \(I-1),
呼叫((L = 1,M = 0),T)。%使用庫(reif)的(=)/ 3和(',')/ 3
結合使用元謂詞的示例查詢1:tfilter/3power_of_two_t/2
?- tfilter(power_of_two_t, [0,2,3,-5,-2,1,8,7,4], Ps).
Ps = [2,1,8,4]. % succeeds deterministically
這是由注釋建議的更一般的查詢:
?- tfilter(power_of_two_t, [X], Ps).
Ps = [X], 0#=X/\_A, _A+1#=X, X in 1..sup, _A in 0..sup
; Ps = [], dif(_A,0), _A#=X/\_B, _B+1#=X, X in 1..sup, _B in 0..sup
; Ps = [], dif(_A,1), _A#=min(X,1), _B#=X/\_C, _C+1#=X, X#>=_A, _A in inf..1.
腳注1:整理了上面顯示的應答序列以指示呼叫的確定性。
腳注2:要重現結果,請使用call_det/2如下定義:
call_det(G_0,Det):-
call_cleanup(G_0,標志=設置),
(nonvar(Flag)
-> Det = true
; Det =假
)。

TA貢獻1808條經驗 獲得超4個贊
在一個謂詞中同時執行兩項如此不同的任務是一件奇怪的事。您可能應該有兩個單獨的謂詞,一個謂詞用于計算2的冪,另一個謂詞用于計算3s。然后,您可以將它們組合成一個謂詞,例如:
check(Nums, MULT2, THREE) :-
count2powers(Nums, MULT2),
count3s(Nums, THREE).
之后,您可以進一步分解并使用單獨的謂詞來檢查數字是否為2的冪:
is2power(1).
is2power(N) :-
N > 0,
N2 is N // 2,
N2 * 2 =:= N,
is2power(N2).
這是基本的軟件工程,通過這種方式,您可以逐步構建程序,并且不僅可以提出“整個程序都返回false”,還可以提出更具體和有意義的問題。
添加回答
舉報