Java lcm lcm(int a, int b)

Here you can find the source of lcm(int a, int b)

Description

Returns the least common multiple of two integers.

License

Open Source License

Parameter

Parameter Description
a the first integer
b the second integer

Return

the LCM of a and b; always positive

Declaration

public static int lcm(int a, int b) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from w  w  w.j  ava2 s . co m
     * Returns the least common multiple of two integers. This method accepts negative arguments.
     * 
     * @param a the first integer
     * @param b the second integer
     * @return the LCM of a and b; always positive
     */
    public static int lcm(int a, int b) {
        int ret = a / gcd(a, b) * b; // reordered to avoid overflow; correctly, a*b / gcd(a, b)
        return (ret < 0 ? -ret : ret);
    }

    /**
     * Returns the greatest common divisor of two integers. This method accepts negative arguments.
     * 
     * @param a the first integer
     * @param b the second integer
     * @return the GCD of a and b; always positive
     */
    public static int gcd(int a, int b) {
        // Fix signs
        a = (a < 0 ? -a : a);
        b = (b < 0 ? -b : b);
        int t = 0;
        while (b != 0) {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }
}

Related

  1. LCM(double a, double b)
  2. lcm(int a, int b)
  3. lcm(int a, int b)
  4. lcm(int a, int b)
  5. lcm(int a, int b)
  6. lcm(int a, int b)
  7. lcm(int a, int b)
  8. lcm(int a, int b)