Returns the least common multiple of two integers. - Java java.lang

Java examples for java.lang:Math Number

Description

Returns the least common multiple of two integers.

Demo Code


//package com.java2s;

public class Main {
    /**/*  w w  w  . ja v a  2s .  c  o  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 Tutorials