Write a function to compute Euclids algorithm for GCD


#1

I am trying to write a function to compute Euclids algorithm using a while loop and a # recursion. But I thing what I have here is the recursion approach, please, how do I write # the while loop function?
Thank you


gcd <- function(a,b){

  if (a == b) 
    return (a)
 else if (a>b) 
    return (gcd( a-b, b))
  else if (a<b) 
    return(gcd(a, b-a))
}


#2

Something like this?

gcd = function(a, b){
  while( b != 0 ){
    t = b
    b = a %% b
    a = t
  }
  return(a)
}

#3

Thanks very much Leon. That worked.

Regards