0
public class Temp{
static int add(int m,int n){
    if(m==0)
        return n+1;
    else if(n==0)
        return add(m-1,1);
    else
        return add(m-1,add(m,n-1));
}
public static void main(String[] a){
    System.out.println(add(3,3));
}
}

I am not able to understand what this function is achieving. The output for (2,2) is 7 and for (3,3) is 61. I understand that the value of n decreases then value of m and then the base case is reached but how can I get the output without running the code for a given input?

3
  • A nice video explayining it. Commented Nov 5, 2015 at 15:40
  • Please add a language tag. Commented Nov 5, 2015 at 15:43
  • Actually the question was about the function and it is the same in any language. Hence I did not add the language tag. Commented Nov 5, 2015 at 15:48

1 Answer 1

1

This is the Ackermann function (https://en.wikipedia.org/wiki/Ackermann_function), an example of non-primitive recursive function.

What do you mean by getting the output without running the code for a given input?

If you wish to compute a given value, I suggest you use a HashMap as a cache so that you can reuse already computed values. Also, I think you'd better use BigInteger values if you use m values greater than 3.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.