Java BigInteger Calculate GCD(BigInteger x, BigInteger y)

Here you can find the source of GCD(BigInteger x, BigInteger y)

Description

GCD

License

Open Source License

Declaration

public static BigInteger GCD(BigInteger x, BigInteger y) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;

public class Main {
    public static BigInteger GCD(BigInteger x, BigInteger y) {
        if (x.equals(BigInteger.ZERO)) {
            return y;
        } else if (y.equals(BigInteger.ZERO)) {
            return x;
        } else if (isEven(x) && isEven(y)) {
            x = x.shiftRight(1);/*from ww w  .  j av a2s .  c  o m*/
            y = y.shiftRight(1);
            return GCD(x, y).shiftLeft(1);
        } else if (isOdd(x) && isEven(y)) {
            return GCD(x, y.shiftRight(1));
        } else if (isOdd(y) && isEven(x)) {
            return GCD(y, x.shiftRight(1));
        } else if (x.compareTo(y) <= 0) {
            return GCD(x, y.subtract(x));
        } else {
            return GCD(y, x.subtract(y));
        }
    }

    private static boolean isEven(BigInteger x) {
        return !isOdd(x);
    }

    private static boolean isOdd(BigInteger x) {
        return x.testBit(0);
    }
}

Related

  1. extractInt(BigInteger bi, int start, int end)
  2. fill(BigInteger[] array, BigInteger value)
  3. first(BigInteger i, BigInteger j)
  4. firstLtSecond(BigInteger first, BigInteger second)
  5. gcd(BigInteger a, BigInteger b)
  6. gcd(BigInteger... values)
  7. gcd(Iterable nums)
  8. gcdEuclides(BigInteger a, BigInteger b)
  9. gcdExtended(BigInteger p, BigInteger q)