Skip to content

Instantly share code, notes, and snippets.

@mgonto
Created September 26, 2012 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgonto/3785983 to your computer and use it in GitHub Desktop.
Save mgonto/3785983 to your computer and use it in GitHub Desktop.
Factorial Tail Rec
object factorial {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
def factorial(n : Int) : Int = {
if (n == 0) 1 else n * factorial(n-1)
} //> factorial: (n: Int)Int
def factorial2(n : Int) : Int = {
def innerFact(n : Int, count : Int, acum : Int) : Int = {
if (n + 1 == count) acum
else innerFact(n, count + 1, acum * count)
}
innerFact(n, 1, 1);
} //> factorial2: (n: Int)Int
factorial(4) //> res0: Int = 24
factorial(5) //> res1: Int = 120
factorial2(4) //> res2: Int = 24
factorial2(5) //> res3: Int = 120
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment