Created
October 2, 2017 11:30
-
-
Save alashow/1226b6176ebbeea4810f8ddd520f6e45 to your computer and use it in GitHub Desktop.
Fibonacci in Kotlin
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
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