Java gcd gcdUsingEuclides(long x, long y)

Here you can find the source of gcdUsingEuclides(long x, long y)

Description

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.

License

Apache License

Declaration

public static final long gcdUsingEuclides(long x, long y) 

Method Source Code

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

public class Main {
    /**//from   w  w w .jav a  2  s  . c  o  m
     * 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.
     * <p>
     * http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm
     */
    public static final long gcdUsingEuclides(long x, long y) {
        long greater = x;
        long smaller = y;
        if (y > x) {
            greater = y;
            smaller = x;
        }

        long result = 0;
        while (true) {
            if (smaller == greater) {
                result = smaller; // smaller == greater
                break;
            }

            greater -= smaller;
            if (smaller > greater) {
                long temp = smaller;
                smaller = greater;
                greater = temp;
            }
        }
        return result;
    }
}

Related

  1. GCDHelper(long a, long b)
  2. gcdMultiple(int[] nums)
  3. gcdPositive(int a, int b)
  4. gcdPositive(int... args)
  5. gcdRec(int a, int b)
  6. gcdUsingRecursion(long a, long b)