Skip to content

Instantly share code, notes, and snippets.

@Jeff-Soares
Last active July 12, 2022 17:03
Show Gist options
  • Save Jeff-Soares/1d019902f22185e438843ff00f424342 to your computer and use it in GitHub Desktop.
Save Jeff-Soares/1d019902f22185e438843ff00f424342 to your computer and use it in GitHub Desktop.
import kotlin.time.ExperimentalTime
import kotlin.time.measureTimedValue
@OptIn(ExperimentalTime::class)
fun main() {
val time = measureTimedValue {
(1L..50L).map(::fibRec).let(::println)
}
println(time)
}
fun fib(num: Long): Long {
return when (num) {
0L -> 0L
1L -> 1L
else -> fib(num - 1) + fib(num - 2)
}
}
tailrec fun fibRec(num: Long, aux: Long = 1, acc: Long = 0): Long {
return when (num) {
0L -> acc
1L -> aux
else -> fibRec(num - 1, acc + aux, aux)
}
}
fun fibonacciFold(n: Int) =
(2 until n).fold(1 to 1) { (prev, curr), _ ->
curr to (prev + curr)
}.second
fun fat(num: Long): Long {
return when (num) {
1L -> num
else -> num * fat(num - 1)
}
}
tailrec fun fatRec(num: Long, acc: Long = 1): Long {
return when (num) {
1L -> acc
else -> fatRec(num - 1, acc * num)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment