Advertisement
ggigio

gcd

Mar 4th, 2014
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.79 KB | None | 0 0
  1. object GCD extends App{
  2.  
  3.   println("GCD is: " + gcd(args(0).toInt, args(1).toInt))
  4.  
  5.   //a and b positive according to how the problem was stated.
  6.   //the solution provided is a direct translation of the hint included in the problem description.
  7.   //the funzion gcd is tail recursive, as such, if the compiler supports tail recursive //optimization,the time and space
  8.   //overhead due to the allocation of a new stack frame for each function's call is reduced/eliminated.
  9. //Since the new b' parameter for each function invocation has a maximum value of b'=b-1, O(b) is an //upper limit on the number of function calls. It is demonstrable that the complexity of this algorithm //is O(log(n)) where n= a + b
  10.   def gcd(a: Int, b: Int): Int =
  11.     if(b == 0)
  12.       a
  13.     else
  14.       gcd(b, a % b)
  15. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement