📜  Kotlin递归函数

📅  最后修改于: 2021-01-05 07:23:29             🧑  作者: Mango

#### Kotlin递归函数

``````fun functionName(){
.. .. ..
functionName() //calling same function
}
``````

#### Kotlin递归函数示例1：有限的时间

``````var count = 0
fun rec(){
count++;
if(count<=5){
println("hello "+count);
rec();
}
}
fun main(args: Array) {
rec();
}
``````

``````hello 1
hello 2
hello 3
hello 4
hello 5
``````

#### Kotlin递归函数示例2：阶乘数

``````fun main(args: Array) {
val number = 5
val result: Long
result = factorial(number)
println("Factorial of \$number = \$result")
}

fun factorial(n: Int): Long {
return if(n == 1){
n.toLong()
}
else{
n*factorial(n-1)
}
}
``````

``````Factorial of 5 = 120
``````

``````factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
``````

#### 一般递归

``````fun main(args: Array) {
var result = recursiveSum(100000)
println(result)
}
fun recursiveSum(n: Long) : Long {
return if (n <= 1) {
n
} else {
n + recursiveSum(n - 1)
}
}
``````

``````Exception in thread "main" java.lang.StackOverflowError
``````

#### Kotlin尾递归示例1：计算nth(100000)个数字的太阳

``````fun main(args: Array) {
var number = 100000.toLong()
var result = recursiveSum(number)
println("sun of upto \$number number = \$result")
}
tailrec fun recursiveSum(n: Long, semiresult: Long = 0) : Long {
return if (n <= 0) {
semiresult
} else {
recursiveSum( (n - 1), n+semiresult)
}
}
``````

``````sun of upto 100000 number = 5000050000
``````

#### Kotlin尾递归示例2：计算数字阶乘

``````fun main(args: Array) {
val number = 4
val result: Long
result = factorial(number)
println("Factorial of \$number = \$result")
}

tailrec fun factorial(n: Int, run: Int = 1): Long {
return if (n == 1){
run.toLong()
} else {
factorial(n-1, run*n)
}
}
``````

``````Factorial of 4 = 24
``````