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?
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).
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.
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? The Ackermann function can only be calculated using a while loop, which keeps repeating an action until an associated test returns false.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With