Created
September 26, 2012 04:13
-
-
Save mgonto/3785983 to your computer and use it in GitHub Desktop.
Factorial Tail Rec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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