Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite Ackermann function in non-recursive style?

I have function

public static int func(int M,int N){
    if(M == 0 || N == 0) return M+N+1;
    return func(M-1, func(M, N-1));
}

How to rewrite it in non-recursive style ? Maybe, is it implementation some algorithm?

like image 777
BILL Avatar asked May 24 '12 17:05

BILL


People also ask

Is Ackermann function recursive?

The Ackermann function is the simplest example of a well-defined total function which is computable but not primitive recursive, providing a counterexample to the belief in the early 1900s that every computable function was also primitive recursive (Dötzel 1991).

Why is Ackermann function not primitive recursive?

The definition of the Ackermann function contains the clause A(m+1,n+1)=A(m,A(m+1,n)). The “next” value of the function (going from n to n+1) depends on calls with larger parameters (starting with A(m+1,n)). So the definition is not in primitive recursive form.

Can Ackermann function be written iteratively?

The Ackermann function can be computed iteratively. However, the Ackermann function is not a primitive recursive function, and this fact is connected to one specific type of iterative computation.

Can Ackermann's function be coded using for or do loops?

Can Ackermann's function be coded using for or do loops? The Ackermann function can only be calculated using a while loop, which keeps repeating an action until an associated test returns false.


2 Answers

Not quite O(1) but definitely non-recursive.

public static int itFunc(int m, int n){
    Stack<Integer> s = new Stack<Integer>;
    s.add(m);
    while(!s.isEmpty()){
        m=s.pop();
        if(m==0||n==0)
            n+=m+1;
        else{
            s.add(--m);
            s.add(++m);
            n--;
        }
    }
    return n;
}
like image 154
Lightyear Buzz Avatar answered Sep 29 '22 17:09

Lightyear Buzz


All the answers posted previously don't properly implement Ackermann.

def acker_mstack(m, n)
  stack = [m]
  until stack.empty?
    m = stack.pop

    if m.zero?
      n += 1
    elsif n.zero?
      stack << m - 1
      n = 1
    else
      stack << m - 1 << m
      n -= 1
    end
  end
  n
end
like image 35
Kache Avatar answered Sep 29 '22 17:09

Kache