805f6710775004b053ac12cfe1f7734bb3be203a
[platform/upstream/gmp.git] / mpz / lcm.c
1 /* mpz_lcm -- mpz/mpz least common multiple.
2
3 Copyright 1996, 2000, 2001, 2005, 2012 Free Software Foundation, Inc.
4
5 This file is part of the GNU MP Library.
6
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
9
10   * the GNU Lesser General Public License as published by the Free
11     Software Foundation; either version 3 of the License, or (at your
12     option) any later version.
13
14 or
15
16   * the GNU General Public License as published by the Free Software
17     Foundation; either version 2 of the License, or (at your option) any
18     later version.
19
20 or both in parallel, as here.
21
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
25 for more details.
26
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library.  If not,
29 see https://www.gnu.org/licenses/.  */
30
31 #include "gmp.h"
32 #include "gmp-impl.h"
33
34 void
35 mpz_lcm (mpz_ptr r, mpz_srcptr u, mpz_srcptr v)
36 {
37   mpz_t g;
38   mp_size_t usize, vsize;
39   TMP_DECL;
40
41   usize = SIZ (u);
42   vsize = SIZ (v);
43   if (usize == 0 || vsize == 0)
44     {
45       SIZ (r) = 0;
46       return;
47     }
48   usize = ABS (usize);
49   vsize = ABS (vsize);
50
51   if (vsize == 1 || usize == 1)
52     {
53       mp_limb_t  vl, gl, c;
54       mp_srcptr  up;
55       mp_ptr     rp;
56
57       if (usize == 1)
58         {
59           usize = vsize;
60           MPZ_SRCPTR_SWAP (u, v);
61         }
62
63       MPZ_REALLOC (r, usize+1);
64
65       up = PTR(u);
66       vl = PTR(v)[0];
67       gl = mpn_gcd_1 (up, usize, vl);
68       vl /= gl;
69
70       rp = PTR(r);
71       c = mpn_mul_1 (rp, up, usize, vl);
72       rp[usize] = c;
73       usize += (c != 0);
74       SIZ(r) = usize;
75       return;
76     }
77
78   TMP_MARK;
79   MPZ_TMP_INIT (g, usize); /* v != 0 implies |gcd(u,v)| <= |u| */
80
81   mpz_gcd (g, u, v);
82   mpz_divexact (g, u, g);
83   mpz_mul (r, g, v);
84
85   SIZ (r) = ABS (SIZ (r));      /* result always positive */
86
87   TMP_FREE;
88 }