home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21fb.zip / octave / SCRIPTS.ZIP / scripts / elfun / gcd.m < prev    next >
Encoding:
Text File  |  1999-10-26  |  2.0 KB  |  82 lines

  1. ## Copyright (C) 1996, 1997 John W. Eaton
  2. ##
  3. ## This file is part of Octave.
  4. ##
  5. ## Octave is free software; you can redistribute it and/or modify it
  6. ## under the terms of the GNU General Public License as published by
  7. ## the Free Software Foundation; either version 2, or (at your option)
  8. ## any later version.
  9. ##
  10. ## Octave is distributed in the hope that it will be useful, but
  11. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. ## General Public License for more details.
  14. ##
  15. ## You should have received a copy of the GNU General Public License
  16. ## along with Octave; see the file COPYING.  If not, write to the Free
  17. ## Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  18. ## 02111-1307, USA.
  19.  
  20. ## -*- texinfo -*-
  21. ## @deftypefn {Mapping Function} {} gcd (@var{x}, @code{...})
  22. ## Compute the greatest common divisor of the elements of @var{x}, or the
  23. ## list of all the arguments.  For example, 
  24. ## 
  25. ## @example
  26. ## gcd (a1, ..., ak)
  27. ## @end example
  28. ## 
  29. ## @noindent
  30. ## is the same as
  31. ## 
  32. ## @example
  33. ## gcd ([a1, ..., ak])
  34. ## @end example
  35. ## 
  36. ## An optional second return value, @var{v}
  37. ## contains an integer vector such that
  38. ## 
  39. ## @example
  40. ## g = v(1) * a(k) + ... + v(k) * a(k)
  41. ## @end example
  42. ## @end deftypefn
  43.  
  44. ## See also: lcm, min, max, ceil, floor.
  45.  
  46. ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at>
  47. ## Created: 16 September 1994
  48. ## Adapted-By: jwe
  49.  
  50. function [g, v] = gcd (a, ...)
  51.  
  52.   if (nargin == 0)
  53.     usage ("[g, v] = gcd (a, ...)");
  54.   endif
  55.  
  56.   if (nargin > 1)
  57.     va_start;
  58.     for k = 2:nargin;
  59.       a = [a, (va_arg ())];
  60.     endfor
  61.   endif
  62.  
  63.   if (round (a) != a)
  64.     error ("gcd: all arguments must be integer");
  65.   endif
  66.  
  67.   g = abs (a(1));
  68.   v = sign (a(1));
  69.   for k = 1:(length (a) - 1)
  70.     x = [g, 1, 0];
  71.     y = [(abs (a(k+1))), 0, 1];
  72.     while (y(1) > 0)
  73.       r = x - y * floor (x(1) / y(1));
  74.       x = y;
  75.       y = r;
  76.     endwhile
  77.     g = x(1);
  78.     v = [x(2) * v, x(3) * (sign (a(k+1)))];
  79.   endfor
  80.  
  81. endfunction
  82.