//普通递归
fun factoril(num:Int):BigInteger{
if(num==0)return BigInteger.valueOf(1L)
else{
return BigInteger.valueOf(num.toLong()).times(factoril(num-1))
}
}
fun main(args: Array<String>) {
println(factoril(5))
}
//尾递归优化处理
class Result(var s:BigInteger=BigInteger.valueOf(1L))
tailrec fun factoril(num:Int,result: Result){
if (num==0){
result.s = result.s.times(BigInteger.valueOf(1L))
//result.s = BigInteger.valueOf(1L) 变成常量了
}else{
result.s = result.s.times(BigInteger.valueOf(num.toLong()))
factoril(num-1,result)
}
}
fun main(args: Array<String>) {
val result = Result()
factoril(5,result)
println(result.s)
}
网友评论