changelog shortlog tags changeset files revisions annotate raw

scripts/elfun/lcm.m

changeset 10289: 4b124317dc38
parent:c1fff751b5a8
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (72 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 1994, 1995, 1996, 1997, 1999, 2000, 2002, 2004, 2005,
2## 2006, 2007, 2008, 2009 John W. Eaton
3##
4## This file is part of Octave.
5##
6## Octave is free software; you can redistribute it and/or modify it
7## under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 3 of the License, or (at
9## your option) any later version.
10##
11## Octave is distributed in the hope that it will be useful, but
12## WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14## General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with Octave; see the file COPYING. If not, see
18## <http://www.gnu.org/licenses/>.
19
20## -*- texinfo -*-
21## @deftypefn {Mapping Function} {} lcm (@var{x})
22## @deftypefnx {Mapping Function} {} lcm (@var{x}, @dots{})
23## Compute the least common multiple of the elements of @var{x}, or
24## of the list of all arguments. For example,
25##
26## @example
27## lcm (a1, @dots{}, ak)
28## @end example
29##
30## @noindent
31## is the same as
32##
33## @example
34## lcm ([a1, @dots{}, ak]).
35## @end example
36##
37## All elements must be the same size or scalar.
38## @seealso{factor, gcd}
39## @end deftypefn
40
41## Author: KH <Kurt.Hornik@wu-wien.ac.at>
42## Created: 16 September 1994
43## Adapted-By: jwe
44
45function l = lcm (varargin)
46
47 if (nargin == 0)
48 print_usage ();
49 endif
50
51 if (nargin == 1)
52 a = varargin{1};
53
54 if (round (a) != a)
55 error ("lcm: all arguments must be integer");
56 endif
57
58 if (any (a) == 0)
59 l = 0;
60 else
61 a = abs (a);
62 l = a (1);
63 for k = 1:(length (a) - 1)
64 l = l * a(k+1) / gcd (l, a(k+1));
65 endfor
66 endif
67 else
68
69 l = varargin{1};
70 sz = size (l);
71 nel = numel (l);
72
73 for i = 2:nargin
74 a = varargin{i};
75
76 if (size (a) != sz)
77 if (nel == 1)
78 sz = size (a);
79 nel = numel (a);
80 elseif (numel (a) != 1)
81 error ("lcm: all arguments must be the same size or scalar");
82 endif
83 endif
84
85 if (round (a) != a)
86 error ("lcm: all arguments must be integer");
87 endif
88
89 idx = find (l == 0 || a == 0);
90 a = abs (a);
91 l = l .* a ./ gcd (l, a);
92 l(idx) = 0;
93 endfor
94 endif
95
96endfunction
97
98%!assert(lcm (3, 5, 7, 15) == lcm ([3, 5, 7, 15]) && lcm ([3, 5, 7,15]) == 105);
99
100%!error lcm ();
101
102%!test
103%! s.a = 1;
104%! fail("lcm (s)");
105