Erlang Mailing Lists

Author Message

<  Erlang questions mailing list  ~  When condition problem (probably newbie question).

andreas at ag.or.at
Posted: Fri Dec 18, 1998 6:20 pm Reply with quote
Guest
Why does the following function not work as intended? It seems like the
test for N being even doesn't work :(

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

28> test:pow(10,3).
{powNeven,10,3}
100

Andreas
--
Win95: n., A huge annoying boot virus that causes random spontaneous system
crashes, usually just before saving a massive project. Easily cured by
UNIX. See also MS-DOS, IBM-DOS, DR-DOS, Win 3.x, Win98.



Post generated using Mail2Forum (http://m2f.sourceforge.net)
mbjk at eecs.umich.edu
Posted: Fri Dec 18, 1998 6:35 pm Reply with quote
Guest
Andreas Kostyrka <andreas_at_ag.or.at> 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


Post generated using Mail2Forum (http://m2f.sourceforge.net)
joe at erix.ericsson.se
Posted: Mon Dec 21, 1998 9:07 am Reply with quote
Guest
> 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.
>



If you look in http://www.erlang.org/examples/examples-2.0.html

And in http://www.erlang.org/examples/examples-2.0.tgz

You'll find 3 modules:

lin.erl - this contains some simple functions for linear
algebra. (including pow/2)

primes.erl - Contains routines for generating large primes.

rsa_key.erl - Shows how a public key crypto system could have been
implemented in Erlang.

--
Joe Armstrong Computer Science Laboratory +46 8 719 9452
AT2/ETX/DN/SU Ericsson Telecom SE-126 25 Stockholm Sweden
joe_at_cslab.ericsson.se http://www.ericsson.se/cslab/~joe



Post generated using Mail2Forum (http://m2f.sourceforge.net)

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum