Prolog int_log2(X,Y),它将Y设置为X的整数log2,其中X被假定为非负整数
我得到了以下任务:Prolog int_log2(X,Y),它将Y设置为X的整数log2,其中X被假定为非负整数,prolog,Prolog,我得到了以下任务: int_log2(X,Y)将Y设置为X的整数log2,其中X被假定为非负整数。例如,int\u log(133,X)将X设置为7。整数log base 2 of X表示将X除以2得到1的次数。其中divide表示整数除法。只需使用+和div即可对其进行编码 这就是我目前得到的。我不是100%确定我是否应该这样做。当我运行queryint_log(133,Z)时,它只显示true或false的答案 div(0,X). div(X,Z) :- X \=0, X1 is X-1,
int_log2(X,Y)
将Y
设置为X的整数log2,其中X
被假定为非负整数。例如,int\u log(133,X)
将X设置为7
。整数log base 2 of X
表示将X
除以2
得到1的次数。其中divide表示整数除法。只需使用+
和div
即可对其进行编码
这就是我目前得到的。我不是100%确定我是否应该这样做。当我运行queryint_log(133,Z)
时,它只显示true或false的答案
div(0,X).
div(X,Z) :- X \=0, X1 is X-1, div(X1,W), Z is floor(X/2).
int_log(0,X).
int_log(X,Z) :- X \= 0, X1 is X-1, int_log(X1,W), div(W,Z).
与这些练习一样,问题陈述已经包含了答案
假定X
为非负整数
。。。将X
除以2得到1的次数
。。。将X
除以2的次数
。。。只使用+
和div
对其进行编码
所以这是这样的:
?- int_log2(133, X).
X = 7 .
?- int_log2(256, X).
X = 8 .
?- int_log2(255, X).
X = 7 .
例如:
?- X is msb(133).
X = 7.
?- X is msb(256).
X = 8.
?-X是msb(133)。
X=7。
?-X是msb(256)。
X=8。
X0 is X div 2, % used `div`
int_log2(X0, Y0),
Y is Y0 + 1. % used `+`
?- int_log2(133, X).
X = 7 .
?- int_log2(256, X).
X = 8 .
?- int_log2(255, X).
X = 7 .
Y is msb(X).
?- X is msb(133).
X = 7.
?- X is msb(256).
X = 8.