Skip to content

Instantly share code, notes, and snippets.

@CheolhoJeon
Created May 8, 2021 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CheolhoJeon/d731cf9ac1c2ba13e604c088a92475c0 to your computer and use it in GitHub Desktop.
Save CheolhoJeon/d731cf9ac1c2ba13e604c088a92475c0 to your computer and use it in GitHub Desktop.
package chap4.Recursion
import atomictest.eq
fun fibonacci(n: Int): Long {
tailrec fun fibonacci(
n: Int,
current: Long,
next: Long
): Long {
if (n == 0) return current
return fibonacci(n - 1, next, current + next)
}
return fibonacci(n, 0L, 1L)
}
fun main() {
(0..8).map { fibonacci(it) } eq
"[0, 1, 1, 2, 3, 5, 8, 13, 21]"
fibonacci(22) eq 17711
fibonacci(50) eq 12586269025
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment