0

I'm trying to write the code which get 3 arguments when X is the coefficient, Y is the exponent and R should return the answer.

My code till now is -

exp(X,0,R):- R is X*X.
exp(X,Y,R):- Y1 is Y-1, exp(X,Y1,R).

I know it doesn't work.

But I can't figure it out.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
divelner
  • 244
  • 1
  • 2
  • 10
  • 1
    You say you know _why_ it doesn't work. Why is it that it doesn't? (Anyway, for exponentiation, you should probably use `R is X^Y`. And how much is something to the power of 0? and to the power of 1?) –  Feb 05 '15 at 10:00
  • 1
    Write your predicates so they are logical if you read them. To say that, *`R` is `X^Y` if `Y1` is `Y-1` and `R` is `X^Y1`* doesn't make mathematical sense, does it? Nor does *`R` is `X^0` if `R` is `X*X`*. – lurker Feb 05 '15 at 10:30
  • 2
    As a point of terminology, in an expression `A * X^Y`, `A` is the *coefficient*, `X` is the *base*, and `Y` is the *exponent*. So in this case, `X` is the *base*. :) – lurker Feb 05 '15 at 11:24

1 Answers1

0

Check this out:

3 ?- X is 5 // 2, Y is 5 rem 2.
X = 2,
Y = 1.
4 ?- 0 is 5 rem 2.
false.

So,

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.

or, in 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 ... 
...

To write the code that you ask for, you just decrement by 1 instead of halving (changing the rest of the code accordingly, of course).

Will Ness
  • 70,110
  • 9
  • 98
  • 181