RosettaCodeData/Task/Fibonacci-sequence/Kotlin/fibonacci-sequence.kotlin

32 lines
701 B
Text
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
enum class Fibonacci {
ITERATIVE {
2017-09-23 10:01:46 +02:00
override fun invoke(n: Long) = if (n < 2) {
2015-11-18 06:14:39 +00:00
n
2017-09-23 10:01:46 +02:00
} else {
var n1 = 0L
var n2 = 1L
2015-11-18 06:14:39 +00:00
var i = n
do {
val sum = n1 + n2
n1 = n2
n2 = sum
} while (i-- > 1)
n1
}
},
RECURSIVE {
override fun invoke(n: Long): Long = if (n < 2) n else this(n - 1) + this(n - 2)
};
abstract operator fun invoke(n: Long): Long
}
2016-12-05 22:15:40 +01:00
fun main(a: Array<String>) {
2015-11-18 06:14:39 +00:00
val r = 0..30L
2016-12-05 22:15:40 +01:00
Fibonacci.values().forEach {
print("${it.name}: ")
r.forEach { i -> print(" " + it(i)) }
println()
2015-11-18 06:14:39 +00:00
}
}