Calculates lowest common multiple (LCM) of two numbers. - Java java.lang

Java examples for java.lang:Math Number

Description

Calculates lowest common multiple (LCM) of two numbers.

Demo Code

// Copyright (C) GridGain Systems, Inc. Licensed under GPLv3, http://www.gnu.org/licenses/gpl.html
//package com.java2s;

public class Main {
    /**//from  ww  w  .j  a v  a2s .  com
     * Calculates lowest common multiple (LCM) of two numbers.
     *
     * @param a First number.
     * @param b Second number.
     * @return Lowest common multiple.
     */
    static int getLCM(int a, int b) {
        int gcd = getGCD(a, b);

        return a * b / gcd;
    }

    /**
     * Calculates greatest common divisor (GCD) of two numbers.
     *
     * @param a First number.
     * @param b Second number.
     * @return Greatest common divisor.
     */
    static int getGCD(int a, int b) {
        int x;
        int y;

        if (a > b) {
            x = a;
            y = b;
        } else {
            x = b;
            y = a;
        }

        int z = x % y;

        return (z == 0) ? y : getGCD(z, y);
    }
}

Related Tutorials