[R] The greatest common divisor between more than two integers

Michael Knudsen micknudsen at gmail.com
Wed Jul 15 10:11:03 CEST 2009


On Wed, Jul 15, 2009 at 8:55 AM, Atte Tenkanen<attenka at utu.fi> wrote:

> Do somebody know if there is a function in R which  computes the greatest common divisor between several (more than two) integers?

Is there a function for computing the greatest common divisor of *two*
numbers? I can't find one, but assume that there is such a function,
and call it gcd. Then you could define a recursive function to do the
job. Something like

new_gcd = function(v)
{
   if (length(v)==2) return(gcd(v))
   else return (new_gcd(v[1],new_gcd(v[2:length(v)]))
}

where v is a vector containing the numbers you want to calculate the
greatest common divisor of.

-- 
Michael Knudsen
micknudsen at gmail.com
http://lifeofknudsen.blogspot.com/




More information about the R-help mailing list