Industrial Training




Recursion Function


Recursion function is a function which calls itself continuously. This technique is called recursion.


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

Kotlin recursion function example 1: Finite times


Let's see an example of recursion function printing count.


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

Output:
hello 1
hello 2
hello 3
hello 4
hello 5

Kotlin recursion function example 2: Factorial Number


Let's see an example of recursion function calculating factorial of number.


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)  
    }  
}

Output:
Factorial of 5 = 120

Working process of above factorial example


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 Tail Recursion


Before we will discuss about the tail recursion, let's try to make an example which calculate sum of nth (100000 larger number) using general (normal) recursion.


General Recursion


Let's see an example of calculating sum of nth (100000 larger number) using general (normal) recursion.


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)  
    }  
} 

Output:
Exception in thread "main" java.lang.StackOverflowError

The above example throws an exception of "java.lang.StackOverflowError". This is because the compiler is unable to call large number of recursive function call.


Tail Recursion


Tail recursion is a recursion which performs the calculation first, then makes the recursive call. The result of current step is passed into the next recursive call.
Tail recursion follows one rule for implementation. This rule is as follow:
The recursive call must be the last call of the method. To declare a recursion as tail recursion we need to use tailrec modifier before the recursive function.


Kotlin Tail Recursion Example 1: calculating sun of nth(100000) number


Let's see an example of calculating sum of nth (100000 larger number) using tail recursion.


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

Output:
sun of upto 100000 number = 5000050000

Kotlin Tail Recursion Example 2: calculating factorial of number


Let's see an example of calculating factorial of number using tail recursion.


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)  
    }  
}   

Output:
Factorial of 4 = 24


Hi I am Pluto.