Saturday, May 24, 2008

Euclid's Algorithm

Euclid's algorithm is one of the oldest, known by ancient Greeks like Aristotle. You might remember it from elementary school when you had to find things like greatest common factor/divisor and least common multiple. Greatest common factor/divisor allowed you to reduce fractions like 4/12 to 1/3. Least common multiple allowed you to add and subtract fractions that had different denominators.


There is more than one way to implement this algorithm. The original involved iterative subtraction. This was later improved upon with iterative modulo division. Another method, the one I'll be using here, is recursion.


ASP

  1. function gcd(byVal a, byVal b)
  2.     a = abs(a)
  3.     b = abs(b)
  4.     if a = 0 then
  5.         gcd = b
  6.     elseif b = 0 then
  7.         gcd = a
  8.     elseif a > b then
  9.         gcd = gcd(b, a mod b)
  10.     else
  11.         gcd = gcd(a, b mod a)
  12.     end if
  13. end function
  14. function lcm(byVal a, byVal b)
  15.     a = abs(a)
  16.     b = abs(b)
  17.     if a > b then
  18.         lcm = (b / gcd(a, b)) * a
  19.     else
  20.         lcm = (a / gcd(a, b)) * b
  21.     end if
  22. end function

PHP

  1. function gcd($a, $b)
  2. {
  3.     $a = abs($a);
  4.     $b = abs($b);
  5.     if ($a == 0)
  6.     {
  7.         return $b;
  8.     }
  9.     elseif ($b == 0)
  10.     {
  11.         return $a;
  12.     }
  13.     elseif ($a > $b)
  14.     {
  15.         return gcd($b, $a % $b);
  16.     }
  17.     else
  18.     {
  19.         return gcd($a, $b % $a);
  20.     }
  21. }
  22. function lcm($a, $b)
  23. {
  24.     $a = abs($a);
  25.     $b = abs($b);
  26.     if ($a > $b)
  27.     {
  28.         return ($b / gcd($a, $b)) * $a;
  29.     }
  30.     else
  31.     {
  32.         return ($a / gcd($a, $b)) * $b;
  33.     }
  34. }

Euclid's algorithm is not always the fastest, but it is the simplest. A better algorithm was devised by 20th century mathematician Dick Lehmer. Another 20th century mathematician, Josef Stein, devised a specialized algorithm for computers which uses bit shifting. Note, however, that the performance improvement of these more modern algorithms varies depending on the CPU and size of the numbers involved. In some cases, Euclid is actually faster.


No comments: