Java lcm lcm(int n, int m)

Here you can find the source of lcm(int n, int m)

Description

Find the least common multiple of n and m.

License

Open Source License

Parameter

Parameter Description
n first number
m second number

Return

the LCM of n and m

Declaration

public static int lcm(int n, int m) 

Method Source Code

//package com.java2s;
/*//from  ww  w  . jav  a  2 s  .  c o  m
 * NOTE: This copyright does *not* cover user programs that use HQ
 * program services by normal system calls through the application
 * program interfaces provided as part of the Hyperic Plug-in Development
 * Kit or the Hyperic Client Development Kit - this is merely considered
 * normal use of the program, and does *not* fall under the heading of
 * "derived work".
 * 
 * Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
 * This file is part of HQ.
 * 
 * HQ is free software; you can redistribute it and/or modify
 * it under the terms version 2 of the GNU General Public License as
 * published by the Free Software Foundation. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

public class Main {
    /**
     * Find the least common multiple of <code>n</code> and
     * <code>m</code>.
     *
     * @param n first number
     * @param m second number
     * @return the LCM of n and m
     */
    public static int lcm(int n, int m) {
        return m * (n / gcd(n, m));
    }

    /**
     * Find the greatest common divisor of both <code>n</code> and
     * <code>m</code>.
     *
     * @param n first number
     * @param m second number
     * @return the GCD of n and m, or 1 if both numbers are 0
     */
    public static int gcd(int n, int m) {
        n = Math.abs(n);
        m = Math.abs(m);

        // avoid infinite recursion
        if (n == 0 && m == 0) {
            return 1;
        }
        if (n == m && n >= 1) {
            return n;
        }

        return (m < n) ? gcd(n - m, n) : gcd(n, m - n);
    }
}

Related

  1. lcm(int a, int b)
  2. lcm(int a, int b)
  3. lcm(int a, int b)
  4. lcm(int m, int n)
  5. LCM(int m, int n)
  6. lcm(int num1, int num2)
  7. lcm(int num1, int num2)
  8. lcm(int numberOne, int numberTwo)
  9. lcm(int p, int q)