2018-09-30 23:01:58 +01:00
---
id: 594810f028c0303b75339acf
2020-11-27 19:02:05 +01:00
title: Ackermann function
2018-09-30 23:01:58 +01:00
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302223
2021-01-13 03:31:00 +01:00
dashedName: ackermann-function
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2019-02-24 19:04:29 +09:00
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
2020-11-27 19:02:05 +01:00
2019-02-24 19:04:29 +09:00
The Ackermann function is usually defined as follows:
2020-11-27 19:02:05 +01:00
$A(m, n) = \\begin{cases} n+1 & \\mbox{if } m = 0 \\\\ A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0. \\end{cases}$
2019-03-01 17:10:50 +09:00
Its arguments are never negative and it always terminates.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --instructions--
2019-03-01 17:10:50 +09:00
Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
`ack` should be a function.
```js
assert(typeof ack === 'function');
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
`ack(0, 0)` should return 1.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(ack(0, 0) === 1);
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`ack(1, 1)` should return 3.
2018-09-30 23:01:58 +01:00
```js
2020-11-27 19:02:05 +01:00
assert(ack(1, 1) === 3);
```
2020-09-15 09:57:40 -07:00
2020-11-27 19:02:05 +01:00
`ack(2, 5)` should return 13.
```js
assert(ack(2, 5) === 13);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
`ack(3, 3)` should return 61.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(ack(3, 3) === 61);
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
function ack(m, n) {
}
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
2019-02-26 17:07:07 +09:00
function ack(m, n) {
2018-09-30 23:01:58 +01:00
return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));
}
```