When condition problem (probably newbie question).

Martin Bjorklund mbjk@REDACTED
Fri Dec 18 19:35:23 CET 1998


Andreas Kostyrka <andreas@REDACTED> wrote:
> Why does the following function not work as intended? It seems like the
> test for N being even doesn't work :(

Well, it does!  But you probably want to test that M is even, not that
N is even.

Also, you will need to handle the case that M is odd.

So the resulting code could look like:

pow(N,0) -> io:write({pow,N,0}), io:nl(), 1;
pow(N,1) -> N;
pow(N,M) when M rem 2 == 0 ->
  io:write({powNeven,N,M}), io:nl(),
  X = pow(N,M div 2), X * X;
pow(N,M) ->  % M is odd, > 1
  X = pow(N,M-1),
  X*N.


I also deleted the clause:

> pow(N,2) -> N * N;

... since that case is taken care of when M rem 2 == 0.




/martin



More information about the erlang-questions mailing list