Continue the development of recursive function theory by defining the following, using guards where it is helpful:
mod(M, N)
is the remainder after dividing M by N (use the convention that mod(M, 0) is 0. (In rex, mod(M, N) is available as M % N, also read M modulo N, or M mod N.)
div(M, N)
is the quotient obtained by dividing M by N (again with div(M, 0) defined to be 0). (In rex, div(M, N) is available as M / N.)
Show how Euclid's algorithm can be sped up if mod were available as a primitive function.
rex> gcd(0, Y) => Y;
gcdrex> gcd(X, Y) => X <= Y ? gcd(mod(Y, X), X);
gcdrex> gcd(X, Y) => gcd(Y, X);
gcdThese rules work precisely as those given in the text except that these subtract out all the X's possible from the Y in one command rather than going through [Y/X] command iterations to do so.
Return |