Java gcd gcd(int n, int m)

Here you can find the source of gcd(int n, int m)

Description

Find the greatest common divisor of both n and m.

License

Open Source License

Parameter

Parameter Description
n first number
m second number

Return

the GCD of n and m, or 1 if both numbers are 0

Declaration

public static int gcd(int n, int m) 

Method Source Code

//package com.java2s;
/*//from  ww w.ja  va2  s  .  co m
 * NOTE: This copyright does *not* cover user programs that use HQ
 * program services by normal system calls through the application
 * program interfaces provided as part of the Hyperic Plug-in Development
 * Kit or the Hyperic Client Development Kit - this is merely considered
 * normal use of the program, and does *not* fall under the heading of
 * "derived work".
 * 
 * Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
 * This file is part of HQ.
 * 
 * HQ is free software; you can redistribute it and/or modify
 * it under the terms version 2 of the GNU General Public License as
 * published by the Free Software Foundation. This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

public class Main {
    /**
     * Find the greatest common divisor of both <code>n</code> and
     * <code>m</code>.
     *
     * @param n first number
     * @param m second number
     * @return the GCD of n and m, or 1 if both numbers are 0
     */
    public static int gcd(int n, int m) {
        n = Math.abs(n);
        m = Math.abs(m);

        // avoid infinite recursion
        if (n == 0 && m == 0) {
            return 1;
        }
        if (n == m && n >= 1) {
            return n;
        }

        return (m < n) ? gcd(n - m, n) : gcd(n, m - n);
    }
}

Related

  1. gcd(int k, int m)
  2. gcd(int largerNumber, int smallerNumber)
  3. gcd(int m, int n)
  4. GCD(int m, int n)
  5. gcd(int m, int n)
  6. gcd(int n1, int n2)
  7. gcd(int num1, int num2)
  8. gcd(int p, int q)
  9. gcd(int p, int q)