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