Ad

Kotlin provides a "tailrec" modifier to auto-optimize recursive functions to while loops (if the function meets criteria).

See:
https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions

Code
Diff
  • tailrec fun fact(n: Int, accumulator: Int): Int = if (n == 0) accumulator else fact(n - 1, n * accumulator)
    
    fun fact(n: Int): Int = fact(n, 1)
    • fun fact(n: Int): Int {
    • var fact = 1
    • var check = n
    • while(check > 0) {
    • fact *= check
    • check--
    • }
    • return fact
    • }
    • tailrec fun fact(n: Int, accumulator: Int): Int = if (n == 0) accumulator else fact(n - 1, n * accumulator)
    • fun fact(n: Int): Int = fact(n, 1)