2847
|
1 ## Copyright (C) 1996, 1997 John W. Eaton |
2313
|
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 |
5307
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
1026
|
19 |
3321
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Mapping Function} {} lcm (@var{x}, @code{...}) |
|
22 ## Compute the least common multiple of the elements elements of @var{x}, or |
3426
|
23 ## the list of all the arguments. For example, |
|
24 ## |
3321
|
25 ## @example |
|
26 ## lcm (a1, ..., ak) |
|
27 ## @end example |
3426
|
28 ## |
3321
|
29 ## @noindent |
|
30 ## is the same as |
3426
|
31 ## |
3321
|
32 ## @example |
|
33 ## lcm ([a1, ..., ak]). |
|
34 ## @end example |
5053
|
35 ## |
|
36 ## All elements must be the same size or scalar. |
5642
|
37 ## @seealso{gcd, min, max, ceil, floor} |
3321
|
38 ## @end deftypefn |
2311
|
39 |
5428
|
40 ## Author: KH <Kurt.Hornik@wu-wien.ac.at> |
2312
|
41 ## Created: 16 September 1994 |
|
42 ## Adapted-By: jwe |
|
43 |
4870
|
44 function l = lcm (varargin) |
904
|
45 |
2601
|
46 if (nargin == 0) |
6046
|
47 print_usage (); |
2601
|
48 endif |
|
49 |
4870
|
50 if (nargin == 1) |
|
51 a = varargin{1}; |
|
52 |
|
53 if (round (a) != a) |
|
54 error ("lcm: all arguments must be integer"); |
|
55 endif |
2325
|
56 |
4870
|
57 if (any (a) == 0) |
|
58 l = 0; |
|
59 else |
|
60 a = abs (a); |
|
61 l = a (1); |
|
62 for k = 1:(length (a) - 1) |
|
63 l = l * a(k+1) / gcd (l, a(k+1)); |
|
64 endfor |
|
65 endif |
|
66 else |
|
67 |
|
68 l = varargin{1}; |
|
69 sz = size (l); |
|
70 nel = numel (l); |
|
71 |
|
72 for i=2:nargin |
|
73 a = varargin{i}; |
2325
|
74 |
4870
|
75 if (size (a) != sz) |
|
76 if (nel == 1) |
|
77 sz = size (a); |
|
78 nel = numel (a); |
|
79 elseif (numel (a) != 1) |
|
80 error ("lcm: all arguments must be the same size or scalar"); |
|
81 endif |
|
82 endif |
|
83 |
|
84 if (round (a) != a) |
|
85 error ("lcm: all arguments must be integer"); |
|
86 endif |
|
87 |
|
88 idx = find (l == 0 || a == 0); |
|
89 a = abs (a); |
|
90 l = l .* a ./ gcd (l, a); |
|
91 l(idx) = 0; |
715
|
92 endfor |
|
93 endif |
2325
|
94 |
715
|
95 endfunction |