Knuth's power tree: Difference between revisions

Added Kotlin
(Added Kotlin)
Line 344:
<lang J> 90j83 ": (x:1.1) usepath 81
2253.24023604401248793730853803334956796672985248117050381481057734540658419009864481100</lang>
 
=={{header|Kotlin}}==
{{trans|Python}}
<lang scala>// version 1.1.3
 
import java.math.BigDecimal
 
var p = mutableMapOf(1 to 0)
var lvl = mutableListOf(listOf(1))
 
fun path(n: Int): List<Int> {
if (n == 0) return emptyList<Int>()
while (n !in p) {
val q = mutableListOf<Int>()
for (x in lvl[0]) {
for (y in path(x)) {
if ((x + y) in p) break
p[x + y] = x
q.add(x + y)
}
}
lvl[0] = q
}
return path(p[n]!!) + n
}
 
fun treePow(x: Double, n: Int): BigDecimal {
val r = mutableMapOf(0 to BigDecimal.ONE, 1 to BigDecimal(x.toString()))
var p = 0
for (i in path(n)) {
r[i] = r[i - p]!! * r[p]!!
p = i
}
return r[n]!!
}
 
fun showPow(x: Double, n: Int, isIntegral: Boolean = true) {
println("$n: ${path(n)}")
val f = if (isIntegral) "%.0f" else "%f"
println("${f.format(x)} ^ $n = ${f.format(treePow(x, n))}\n")
}
 
fun main(args: Array<String>) {
for (n in 0..17) showPow(2.0, n)
showPow(1.1, 81, false)
showPow(3.0, 191)
}</lang>
 
{{out}}
<pre>
0: []
2 ^ 0 = 1
 
1: [1]
2 ^ 1 = 2
 
2: [1, 2]
2 ^ 2 = 4
 
3: [1, 2, 3]
2 ^ 3 = 8
 
4: [1, 2, 4]
2 ^ 4 = 16
 
5: [1, 2, 4, 5]
2 ^ 5 = 32
 
6: [1, 2, 4, 6]
2 ^ 6 = 64
 
7: [1, 2, 4, 6, 7]
2 ^ 7 = 128
 
8: [1, 2, 4, 8]
2 ^ 8 = 256
 
9: [1, 2, 4, 8, 9]
2 ^ 9 = 512
 
10: [1, 2, 4, 8, 10]
2 ^ 10 = 1024
 
11: [1, 2, 4, 8, 10, 11]
2 ^ 11 = 2048
 
12: [1, 2, 4, 8, 12]
2 ^ 12 = 4096
 
13: [1, 2, 4, 8, 12, 13]
2 ^ 13 = 8192
 
14: [1, 2, 4, 8, 12, 14]
2 ^ 14 = 16384
 
15: [1, 2, 4, 8, 12, 14, 15]
2 ^ 15 = 32768
 
16: [1, 2, 4, 8, 16]
2 ^ 16 = 65536
 
17: [1, 2, 4, 8, 16, 17]
2 ^ 17 = 131072
 
81: [1, 2, 4, 8, 16, 32, 64, 80, 81]
1.100000 ^ 81 = 2253.240236
 
191: [1, 2, 4, 8, 16, 32, 64, 128, 160, 176, 184, 188, 190, 191]
3 ^ 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
 
=={{header|Perl}}==
9,476

edits