Created
March 7, 2018 13:23
-
-
Save kmdsbng/034153cec0a918707bfc21f69a3db0e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(argv: Array<String>) { | |
println(fib(1)) | |
println(fib(2)) | |
println(fib(10)) | |
println(fib(100)) | |
} | |
fun fib(end: Int): Long { | |
if (end == 0) { | |
return 0L | |
} | |
if (end == 1) { | |
return 1L | |
} | |
return fibIter(2, end, 1L, 0L) | |
} | |
tailrec fun fibIter(cur: Int, end: Int, last: Long, last2: Long): Long { | |
if (end <= cur) { | |
return last + last2 | |
} | |
return fibIter(cur + 1, end, last + last2, last) | |
} | |
// Warning: A function is marked as tail-recursive but no tail calls are found. | |
tailrec fun fibIterFailed(cur: Int, end: Int, last: Long, last2: Long): Long { | |
if (end <= cur) { | |
return last + last2 | |
} | |
return fibIter(cur + 1, end, last + last2, last) + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment