jaytea commented on a Page, Least Common Multiple  -  Apr 22, 2011

not quite optimized since you're still calling $gettok() and $numtok() many more times than necessary - set them to local variables if you're sure their values won't change across multiple calls. not to mention the method is slow in and of itself :P

a quick method for calculating the LCM of a list of integers is to note that LCM(a, b, c, ...) = LCM(LCM(a, b), c, ...), and that LCM(a, b) = a * b / GCD(a, b) where GCD() is the greatest common divisor and can be found using a very simple algorithm:

alias gcd {
  while ($2) tokenize 32 $2 $calc($1 % $2)
  return $1
} 

then $lcm() can be defined as:

alias lcm {
  var %i = 2, %lcm = $gettok($1, 1, 32)
  while ($gettok($1, %i, 32) != $null) {
    %lcm = $lcm_($v1, %lcm)
    inc %i
  }
  return %lcm
}

alias lcm_ {
  return $calc($1 * $2 / $gcd($1, $2))
}

where $lcm_() calculates the LCM of a pair of integers.

this is much more optimal and even lets you do away with requiring a value for $2, which shouldn't be necessary.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.