Returns the greatest common divisor of a, b. Returns 0 if a == 0 && b == 0. @throws IllegalArgumentException if a < 0 or b < 0
(long a, long b)
| 572 | |
| 573 | |
| 574 | public static long gcd(long a, long b) { |
| 575 | /* |
| 576 | * The reason we require both arguments to be >= 0 is because otherwise, what do you return on |
| 577 | * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't an |
| 578 | * int. |
| 579 | */ |
| 580 | checkNonNegative("a", a); |
| 581 | checkNonNegative("b", b); |
| 582 | if (a == 0) { |
| 583 | // 0 % b == 0, so b divides a, but the converse doesn't hold. |
| 584 | // BigInteger.gcd is consistent with this decision. |
| 585 | return b; |
| 586 | } else if (b == 0) { |
| 587 | return a; // similar logic |
| 588 | } |
| 589 | /* |
| 590 | * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is |
| 591 | * >60% faster than the Euclidean algorithm in benchmarks. |
| 592 | */ |
| 593 | |
| 594 | int aTwos = Long.numberOfTrailingZeros(a); |
| 595 | a >>= aTwos; // divide out all 2s |
| 596 | int bTwos = Long.numberOfTrailingZeros(b); |
| 597 | b >>= bTwos; // divide out all 2s |
| 598 | while (a != b) { // both a, b are odd |
| 599 | // The key to the binary GCD algorithm is as follows: |
| 600 | // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). |
| 601 | // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. |
| 602 | |
| 603 | // We bend over backwards to avoid branching, adapting a technique from |
| 604 | // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax |
| 605 | long delta = a - b; // can't overflow, since a and b are nonnegative |
| 606 | long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); |
| 607 | // equivalent to Math.min(delta, 0) |
| 608 | a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) |
| 609 | // a is now nonnegative and even |
| 610 | b += minDeltaOrZero; // sets b to min(old a, b) |
| 611 | a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b |
| 612 | } |
| 613 | return a << min(aTwos, bTwos); |
| 614 | } |
| 615 | |
| 616 | /** |
| 617 | * Returns the sum of {@code a} and {@code b}, provided it does not overflow. |
no test coverage detected