我正在尝试编写当X是系数时得到3个参数的代码,Y是指数,R应该返回答案。
我的代码到现在为 -
exp(X,0,R):- R is X*X.
exp(X,Y,R):- Y1 is Y-1, exp(X,Y1,R).
我知道它不起作用。
但我无法理解。
答案 0 :(得分:0)
检查出来:
3 ?- X is 5 // 2, Y is 5 rem 2.
X = 2,
Y = 1.
4 ?- 0 is 5 rem 2.
false.
所以,
R being X^Y is the same as
R being .....
when Y is 0, OR
R being .....
when Y is 1, OR
R being R2*R2 and R2 being X^Y2
when Y is even, Y2 is Y // 2, OR
R being ..... and R2 being X^Y2
when Y is odd, Y2 is (Y-1) // 2.
或者,在Prolog中,
is_power(R,X,Y):- Y is 0, R is ... .
is_power(R,X,Y):- Y is 1, R is ... .
is_power(R,X,Y):- Y > 1, ... , is_power(R2,X,Y2), R is ...
...
要编写您要求的代码,您只需递减1而不是减半(当然,相应地更改其余代码)。