List of utility methods to do gcd
int | gcdPositive(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); ... |
int | gcdPositive(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; ... |
int | gcdRec(int a, int b) Recursive approach for finding greatest common divisor using Euclid's algorithm. return (b == 0) ? a : gcdRec(b, a % b);
|
long | gcdUsingEuclides(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) { ... |
long | gcdUsingRecursion(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);
|