Java lcm lcm(int num1, int num2)

Here you can find the source of lcm(int num1, int num2)

Description

Returns the least common multiple of two integers.

License

LGPL

Parameter

Parameter Description
num1 The first number
num2 The second number

Return

The least common multiple

Declaration

public static int lcm(int num1, int num2) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    /**//from  ww w  . j av  a 2s.  com
     * Returns the least common multiple of two integers.
     * 
     * @param num1 The first number
     * @param num2 The second number
     * @return The least common multiple
     */
    public static int lcm(int num1, int num2) {
        if (num1 == 0 || num2 == 0)
            return 0;
        return num1 * num2 / gcd(num1, num2);
    }

    /**
     * Returns the greatest common divisor of two integers.
     * 
     * @param num1 The first number
     * @param num2 The second number
     * @return The greatest common divisor
     */
    public static int gcd(int num1, int num2) {
        if (num1 < 0)
            num1 = -num1;
        if (num2 < 0)
            num2 = -num2;
        return privGCD(num1, num2);
    }

    /**
     * Returns the greatest common divisor of two non-negative integers.
     * 
     * @param num1 The first number; must be non-negative
     * @param num2 The second number; must be non-negative
     * @return The greatest common divisor
     */
    private static int privGCD(int num1, int num2) {
        if (num1 == 0 && num2 == 0)
            return 1;
        if (num1 == 0)
            return num2;
        if (num2 == 0)
            return num1;
        return num1 > num2 ? privGCD(num1 % num2, num2) : privGCD(num1, num2 % num1);
    }
}

Related

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