# 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
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
``````