MuPAD Pro Computing Essentials, 2nd Edition

Example 5.2 The Euclid algorithm to find GCD of two integers

Here is a very simple procedure for the Euclid algorithm.

Euclid := proc(a,b)
begin
   while a <> b do
      if a > b then
         a := a - b
      else
         b := b - a
      end
   end;
   return(a);
end:
 
Euclid(215,125)

5


Here is a more complete example of a procedure for the Euclid algorithm. Some basic protection of data type checking was implemented.

euclid := proc(a,b)
local u,v;
begin
   if testtype(a,Type::Integer) and
      testtype(b,Type::Integer)
   then
      u := abs(a);
      v := abs(b);
      while u<>v do
         if u>v then
            u := u - v
         else
            v := v - u
         end
      end;
      return(u);
   else
      error("use integer numbers")
   end;
end:
  
euclid(12355,23450)
 

35

 

© Miroslaw Majewski, Abu Dhabi,  Update  26-10-2004