KT
kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Schundlabua posted a response to:
// https://www.sololearn.com/Discuss/1111022
// Here's an interesting one: The ackermann function.
// It was designed to grow super quickly - wikipedia says A(4,2) has ~20 000 digits - but it always stops and won't get stuck in a loop. It belongs to a nasty breed of recursive function (non-primitive recursive) that can't be represented well without recursion.
import java.util.Random
val random = Random()
var count = 0
// Get a random number in the range
fun rand(from: Int, to: Int) = random.nextInt(
to-from+1)+from
// Ackermann function recursive implementation with
// debugging. Keep tract of our recursion nesting
// level plus how many times we're called.
fun A(l: Int, m: Int, n: Int): Int =
if (m == 0) {
count += 1
println("A($l, $m, $n)=${n+1}")
n+1
} else if (n == 0) {
count += 1
println("A($l, $m, $n)=A(${l+1}, ${m-1}, 1)")
A(l+1, m-1, 1)
} else {
count += 1
println("A($l, $m, $n)=A(${l+1}, ${m-1}, A(${l+1}, $m, ${n-1}))")
A(l+1, m-1, A(l+1, m, n-1))
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run