3 ways to get greatest common divisor (gcd)

        static int GetGCD(int a, int b)
        {
            int k = a;
            if (a > b)
                k = b;
            while (! ((a%k == 0) && (b%k == 0)))
                k–;
            return k;
        }
 
        static int GetGCDByEuclidean(int a, int b)
        {
            if (a > b)
                return InternalGetGCDByEaclidean(a, b);
            else return InternalGetGCDByEaclidean(b, a);
        }
 
        static int InternalGetGCDByEaclidean(int g, int s)
        {
            if (s == 0)
                return g;
            return InternalGetGCDByEaclidean(s, g % s);
        }
 
        static int GetGCDByEuclidean2(int a, int b)
        {
            while(!((a == 0)||(b == 0)))
            {
                if (a > b)
                    a = a – b;
                else b = b – a;
            }
            if (a != 0)
                return a;
            else return b;
        }
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s