EKG sequence convergence: Difference between revisions

Added Kotlin
(→‎{{header|zkl}}: added code)
(Added Kotlin)
Line 106:
EKG(5): [1 5 10 2 4 6 3 9 12 8]
EKG(7): [1 7 14 2 4 6 3 9 12 8]
 
EKG(5) and EKG(7) converge at term 21
</pre>
 
=={{header|Kotlin}}==
{{trans|Go}}
<lang scala>// Version 1.2.60
 
fun gcd(a: Int, b: Int): Int {
var aa = a
var bb = b
while (aa != bb) {
if (aa > bb)
aa -= bb
else
bb -= aa
}
return aa
}
 
const val LIMIT = 100
 
fun main(args: Array<String>) {
val starts = listOf(2, 5, 7)
val ekg = Array(3) { IntArray(LIMIT) }
 
for ((s, start) in starts.withIndex()) {
ekg[s][0] = 1
ekg[s][1] = start
nextMember@ for (n in 2 until LIMIT) {
var i = 2
while (true) {
// a potential sequence member cannot already have been used
// and must have a factor in common with previous member
if (!ekg[s].slice(0 until n).contains(i) &&
gcd(ekg[s][n - 1], i) > 1) {
ekg[s][n] = i
continue@nextMember
}
i++
}
}
System.out.printf("EKG(%d): %s\n", start, ekg[s].slice(0 until 10))
}
 
// now compare EKG5 and EKG7 for convergence
for (i in 1 until LIMIT) {
if (ekg[1][i] == ekg[2][i] &&
ekg[1].slice(0 until i).sorted() == ekg[2].slice(0 until i).sorted()) {
println("\nEKG(5) and EKG(7) converge at term ${i + 1}")
return
}
}
println("\nEKG5(5) and EKG(7) do not converge within $LIMIT terms")
}</lang>
 
{{output}}
<pre>
EKG(2): [1, 2, 4, 6, 3, 9, 12, 8, 10, 5]
EKG(5): [1, 5, 10, 2, 4, 6, 3, 9, 12, 8]
EKG(7): [1, 7, 14, 2, 4, 6, 3, 9, 12, 8]
 
EKG(5) and EKG(7) converge at term 21
9,488

edits