Rule to calculate power of a number when the exponent is Negative in Prolog?

前端 未结 3 1870
北恋
北恋 2021-01-16 15:19

I have a power function pow that attempts to calculate the value of B to the power of E. So far I handle the cases-
1. exponent i

3条回答
  •  离开以前
    2021-01-16 15:23

    Don't forget that a^(2b) = (a^b)^2 and x^2 = x*x. It is ok to call a tail-recursive working predicate with accumulator, in a non-tail fashion, from a top-level "UI" predicate. That way you don't have to implement working predicate for negative powers but rather reuse the one for positive power, and alter its result in the top-level predicate (I see this has already been suggested):

    pow(B, E, R):- E<0 -> ... ; E=:=0 -> ... ; E>0 -> ... .
    

提交回复
热议问题