Computes the GCD (greatest common divisor) of a and b. - Java java.lang

Java examples for java.lang:Math Calculation

Description

Computes the GCD (greatest common divisor) of a and b.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 Matthias-M. Christen, University of Basel, Switzerland.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * //from   ww  w .  j ava  2s  . c om
 * Contributors:
 *     Matthias-M. Christen, University of Basel, Switzerland - initial API and implementation
 ******************************************************************************/

public class Main{
    /**
     * Computes the GCD (greatest common divisor) of <code>a</code> and
     * <code>b</code>.
     * 
     * @param a
     *            The first number
     * @param b
     *            The second number
     * @return The GCD of <code>a</code> and <code>b</code>
     */
    public static int getGCD(int a, int b) {
        int a0 = a;
        int b0 = b;

        if (b0 > a0) {
            // swap the arguments
            int nTmp = a0;
            a0 = b0;
            b0 = nTmp;
        }

        // ensure that the arguments are non-negative
        if (a0 < 0)
            a0 = -a0;
        if (b0 < 0)
            b0 = -b0;

        // Euclidean algorithm
        for (int p; b0 != 0;) {
            p = a0;
            a0 = b0;
            b0 = p % b0;
        }

        return a0;
    }
    /**
     * Computes the GCD (greatest common divisor) of the numbers
     * <code>rgNumbers</code>.
     * 
     * @param rgNumbers
     *            The numbers for which to compute the least common multiple
     * @return The GCD of <code>rgNumbers</code>
     */
    public static int getGCD(int... rgNumbers) {
        if (rgNumbers.length == 0)
            return 0;
        if (rgNumbers.length == 1)
            return rgNumbers[0];

        int nGCD = rgNumbers[0];
        for (int i = 1; i < rgNumbers.length; i++)
            nGCD = MathUtil.getGCD(nGCD, rgNumbers[i]);

        return nGCD;
    }
}

Related Tutorials