Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Computing Ackerman number for inputs in JavaScript
Ackermann Function
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.
Problem
We are required to write a JavaScript function that takes in two numbers, m and n as the first and the second argument. Our function should return the Ackermann number A(m,n) defined by
A(m,n) = n+1 if m=0 A(m,n) = A(m-1,1) if m>0 , n=0 A(m,n) = A(m-1,A(m,n-1)) if m,n > 0
Example
const m = 12;
const n = 11;
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)))
}
}
console.log(ackermann(m, n));Advertisements