# Kotlin遞歸函數

``````fun functionName(){
.. .. ..
functionName() //調用函數自身
}``````

Kotlin遞歸函數示例1：有限次數

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

``````count => 1
count => 2
count => 3
count => 4
count => 5``````

Kotlin遞歸函數示例2：階乘數

``````fun main(args: Array<String>) {
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``````

## Kotlin尾遞歸

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

``````.....
jdk7.jar;C:\Users\hema\.IdeaIC2018.3\config\plugins\Kotlin\kotlinc\lib\kotlin-stdlib-jdk8.jar" HelloWorldKt
Exception in thread "main" java.lang.StackOverflowError
at HelloWorldKt.recursiveSum(HelloWorld.kt:9)
at HelloWorldKt.recursiveSum(HelloWorld.kt:9)
at HelloWorldKt.recursiveSum(HelloWorld.kt:9)``````

#### 尾遞歸

Kotlin尾遞歸示例1：計算n(100000)個整數之和

``````fun main(args: Array<String>) {
var number = 100000.toLong()
var result = recursiveSum(number)
println("sum 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)
}
}``````

``sum of upto 100000 number = 5000050000``

Kotlin尾遞歸示例2：計算數字階乘

``````fun main(args: Array<String>) {
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``
0 條評論，你可以發表評論，我們會進行改進