Jump to content

Fibonacci sequence: Difference between revisions

→‎{{header|Kotlin}}: Upkeep code: add caching, s/invoke/get/, s/while(--n)/repeat(n)/, s/col.foreach{name ->} -> for (name in col) {...}/
(→‎{{header|Kotlin}}: Upkeep code: add caching, s/invoke/get/, s/while(--n)/repeat(n)/, s/col.foreach{name ->} -> for (name in col) {...}/)
Line 5,813:
 
=={{header|Kotlin}}==
<lang scalakotlin>enum class Fibonacci {
ITERATIVE {
override fun invokeget(n: LongInt): Long = if (n < 2) {
n.toLong()
} else {
var n1 = 0L
var n2 = 1L
varrepeat(n) i = n{
do {
val sum = n1 + n2
n1 = n2
n2 = sum
} while (i-- > 1)
n1
}
},
RECURSIVE {
override fun invokeget(n: LongInt): Long = if (n < 2) n.toLong() else this([n - 1)] + this([n - 2)]
};,
CACHING {
 
val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)
abstract operator fun invoke(n: Long): Long
override fun get(n: Int): Long = cache.computeIfAbsent(n) { this[it-1] + this[it-2] }
},
;
abstract operator fun invokeget(n: LongInt): Long
}
 
fun main(a: Array<String>) {
val r = 0..30L30
for (fib in Fibonacci.values().forEach) {
print("${itfib.name.padEnd(10)}: ")
r.forEach {for (i ->in r) { print(" " + it(fib[i)]) }
println()
}
Line 5,846 ⟶ 5,850:
{{out}}
<pre>ITERATIVE: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
RECURSIVE: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</pre>
CACHING : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
</pre>
 
=={{header|L++}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.