Java Utililty Methods gcd

List of utility methods to do gcd

Description

The list of methods to do gcd are organized into topic(s).

Method

intgcdPositive(int a, int b)
Computes the greatest common divisor of two positive numbers (this precondition is not checked and the result is undefined if not fulfilled) using the "binary gcd" method which avoids division and modulo operations.
if (a == 0) {
    return b;
} else if (b == 0) {
    return a;
final int aTwos = Integer.numberOfTrailingZeros(a);
a >>= aTwos;
final int bTwos = Integer.numberOfTrailingZeros(b);
...
intgcdPositive(int... args)
Returns the greatest common divisor of the given absolute values.
if (args == null || args.length < 2)
    throw new IllegalArgumentException("gcdPositive requires at least two arguments");
int result = args[0];
int n = args.length;
for (int i = 1; i < n; i++) {
    result = gcdPositive(result, args[i]);
return result;
...
intgcdRec(int a, int b)
Recursive approach for finding greatest common divisor using Euclid's algorithm.
return (b == 0) ? a : gcdRec(b, a % b);
longgcdUsingEuclides(long x, long y)
A much more efficient method is the Euclidean algorithm, which uses a division algorithm such as long division in combination with the observation that the gcd of two numbers also divides their difference.
long greater = x;
long smaller = y;
if (y > x) {
    greater = y;
    smaller = x;
long result = 0;
while (true) {
...
longgcdUsingRecursion(long a, long b)
Calculate greatest common divisor of two numbers using recursion.
a = Math.abs(a);
b = Math.abs(b);
return a == 0 ? b : gcdUsingRecursion(b % a, a);