Skip to content

Instantly share code, notes, and snippets.

@alashow
Created October 2, 2017 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alashow/1226b6176ebbeea4810f8ddd520f6e45 to your computer and use it in GitHub Desktop.
Save alashow/1226b6176ebbeea4810f8ddd520f6e45 to your computer and use it in GitHub Desktop.
Fibonacci in Kotlin
package tm.alashow.homework.datastructures.second.kt
import java.math.BigInteger
fun main(args: Array<String>) {
Fibonacci.init()
}
object Fibonacci {
fun init() {
// forever and ever
while (true) {
print("Enter Fn: ")
val n = try { readLine()!!.toLong() } catch (e: Exception) { 10L }
println("\nFibonacci '$n': ")
// seed is 0 and 1
fibonacci(BigInteger.ZERO, BigInteger.ONE, BigInteger.valueOf(n))
//double space
println("\n")
}
}
/**
* Calculates and prints each step of Fibonacci using tail recursion.
*
* tailrec modifier used to use tail recursion optimization.
*/
tailrec private fun fibonacci(a: BigInteger, b: BigInteger, n: BigInteger): BigInteger {
print("$a, ")
return if (n == BigInteger.ZERO) a else fibonacci(b, a + b, n - BigInteger.ONE)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment