Computing Ackerman number for inputs in JavaScript

The Ackermann Function is a classic example of a recursive function that grows extremely quickly. It's notable for being a total computable function that is not primitive recursive, making it an important concept in theoretical computer science.

Problem Statement

We need to write a JavaScript function that takes two non-negative integers, m and n, and returns the Ackermann number A(m,n) defined by the following mathematical definition:

A(m,n) = n+1 if m=0
A(m,n) = A(m-1,1) if m>0 and n=0
A(m,n) = A(m-1,A(m,n-1)) if m>0 and n>0

Implementation

Here's the JavaScript implementation of the Ackermann function:

const ackermann = (m, n) => {
    if (m === 0) {
        return n + 1;
    }
    if (n === 0) {
        return ackermann(m - 1, 1);
    }
    if (m > 0 && n > 0) {
        return ackermann(m - 1, ackermann(m, n - 1));
    }
};

// Test with small values
console.log("A(0, 0) =", ackermann(0, 0));
console.log("A(1, 1) =", ackermann(1, 1));
console.log("A(2, 2) =", ackermann(2, 2));
console.log("A(3, 1) =", ackermann(3, 1));
A(0, 0) = 1
A(1, 1) = 3
A(2, 2) = 7
A(3, 1) = 13

How It Works

The function follows the mathematical definition exactly:

  • Base case (m = 0): Returns n + 1
  • Recursive case 1 (n = 0): Calls ackermann(m-1, 1)
  • Recursive case 2 (m > 0, n > 0): Calls ackermann(m-1, ackermann(m, n-1))

Growth Rate Demonstration

// Show how quickly values grow
for (let m = 0; m 

A(0, 0) = 1
A(0, 1) = 2
A(0, 2) = 3
A(0, 3) = 4
---
A(1, 0) = 2
A(1, 1) = 3
A(1, 2) = 4
A(1, 3) = 5
---
A(2, 0) = 3
A(2, 1) = 5
A(2, 2) = 7
A(2, 3) = 9
---
A(3, 0) = 5
A(3, 1) = 13
A(3, 2) = 29
A(3, 3) = 61
---

Important Note

The Ackermann function grows extremely rapidly. Values like A(4,2) or higher will cause stack overflow errors or take impractically long to compute. Use small input values for testing.

Conclusion

The Ackermann function demonstrates deep recursion and exponential growth. While mathematically fascinating, it's computationally expensive and should be used with very small input values to avoid performance issues.

Updated on: 2026-03-15T23:19:00+05:30

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements