Two ways to implement the GCD

ddanbe 0 Tallied Votes 403 Views Share

Most of the time there are many ways to implement an algorithm.
Here are two ways to implement the greatest common divisor algoritm, one of the oldest algorithms ever.

//recursive method
    //
    public static int gcd(int x, int y)
        {
            if (y == 0) return x;
            else return gcd(y, x % y);  
        }


    //more like the ancient greek Euclid originally devised it
    //
    public static int gcd2(int x, int y)
        {
            while (x != y)
            {
                if (x > y)
                {
                    x = x - y;
                }
                else
                {
                    y = y - x;
                }
            }
         return x;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.