Java gcd gcd(long a, long b)

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

Description

Calculates greatest common divisor (GCD) of two integer values a and b

License

LGPL

Parameter

Parameter Description
a Value a
b Value b

Declaration

public static long gcd(long a, long b) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    /**//from   ww  w .j  a  v  a  2 s.  c om
     * Calculates greatest common divisor (GCD) of two integer values
     * <code>a</code> and <code>b</code>
     * 
     * @param a
     *            Value a
     * @param b
     *            Value b
     */
    public static long gcd(long a, long b) {
        if (a == 0)
            return b;
        if (b == 0)
            return a;
        if (a == b)
            return a;
        if (a == 1 | b == 1)
            return 1;
        if ((a % 2 == 0) & (b % 2 == 0))
            return 2 * gcd(a / 2, b / 2);
        if ((a % 2 == 0) & (b % 2 != 0))
            return gcd(a / 2, b);
        if ((a % 2 != 0) & (b % 2 == 0))
            return gcd(a, b / 2);
        return gcd(b, Math.abs(a - b));
    }
}

Related

  1. gcd(int x1, int x2)
  2. gcd(int[] array)
  3. gcd(Integer... values)
  4. GCD(long a, long b)
  5. gcd(long a, long b)
  6. gcd(long a, long b)
  7. gcd(long a, long b)
  8. GCD(long a, long b)
  9. gcd(long a, long b)