Tags

Some code to compute the greatest common divisor and least common multiple of two numbers using R.

gcd <- function(a, b)
{
  a=as.integer(a)
  b=as.integer(b)
  stopifnot(!(a==0 && b==0))
  if ( a == 0 )
    return(b)

  if ( b == 0 )
    return(a)

  return(abs(gcd(b, a-b*floor(a/b))))
}

lcm <- function(a, b)
{
  a=as.integer(a)
  b=as.integer(b)
  return(abs(a*b)/gcd(a,b))
}
Advertisements