65.9K
CodeProject is changing. Read more.
Home

Fast Greatest Common Divisor (GCD) Algorithm

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Feb 14, 2011

CPOL
viewsIcon

34560

/// /// Find the Greatest Common Divisor /// /// Number a /// Number b /// The greatest common Divisor public static long GCD(long a, long b) ...

       /// <summary>
       /// Find the Greatest Common Divisor
       /// </summary>
       /// <param name="a">Number a</param>
       /// <param name="b">Number b</param>
       /// <returns>The greatest common Divisor</returns>
       public static long GCD(long a, long b)
       {
           while (b != 0)
           {
               long tmp = b;
               b = a % b;
               a = tmp;
           }

           return a;
       }

       /// <summary>
       /// Find the Least Common Multiple
       /// </summary>
       /// <param name="a">Number a</param>
       /// <param name="b">Number b</param>
       /// <returns>The least common multiple</returns>
       public static long LCM(long a, long b)
       {
           return (a * b) / GCD(a,b);
       }