Home  >  Article  >  Web Front-end  >  Calculate Ackermann number for input in JavaScript

Calculate Ackermann number for input in JavaScript

PHPz
PHPzforward
2023-08-24 13:09:171176browse

计算 JavaScript 中输入的阿克曼数

Ackermann function

The Ackermann function is a classic example of a recursive function, especially noteworthy because it is not a primitive recursive function. Its value grows very quickly, as does the size of its call tree.

Question

We need to write a JavaScript function that accepts two numbers m and n as the first and the second argument. Our function should return the defined Ackermann number A(m,n) 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));

The above is the detailed content of Calculate Ackermann number for input in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete