Java gcd gcd(int a, int b)

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

Description

Returns the Greatest Common Division using a recursive algorithm based on the Euclides theorem.

License

Open Source License

Parameter

Parameter Description
a the first number, positive.
b the second number, positive.

Return

The Greatest Common Division of the input numbers.

Declaration

public static int gcd(int a, int b) 

Method Source Code

//package com.java2s;
/*//from   w  ww . j  av a 2 s. c  om
 *  This file is part of libtrails.
 *  libtrails is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  libtrails is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with libtrails.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Returns the Greatest Common Division using a recursive algorithm based
     * on the Euclides theorem.
     * @param a the first number, positive.
     * @param b the second number, positive.
     * @return The Greatest Common Division of the input numbers.
     */
    public static int gcd(int a, int b) {
        int min = Math.min(a, b);
        int max = Math.max(a, b);

        int r = max % min;
        if (r == 0) {
            return min;
        } else {
            return gcd(min, r);
        }
    }
}

Related

  1. gcd(final int p, final int q)
  2. gcd(int a, int b)
  3. gcd(int a, int b)
  4. gcd(int a, int b)
  5. gcd(int a, int b)
  6. gcd(int a, int b)
  7. gcd(int a, int b)
  8. gcd(int a, int b)
  9. gcd(int a, int b)