-1

I want to change this function of nested recursion to linear recursion or optimally is tail recursion.

long long x(int n) {
    if (n == 0) return 1;
    int ret = 0;
    for (int i = 0; i < n; ++i) {
        ret += (n - i) * (n - i) * x(i);
    }
    return ret;
}

the origin recursion is

X(0)=1; X(n)=n^2*X(0)+(n-1)^2*X1+...+1^2*X(n-1)
6
  • Why? What is the problem you have? Commented Apr 8, 2023 at 7:56
  • @Someprogrammerdude i implement a recursion function to solve the X(n) Commented Apr 8, 2023 at 8:01
  • @Someprogrammerdude the origin recursion is X(0)=1; X(n)=n^2*X(0)+(n-1)^2*X1+...+1^2*X(n-1) Commented Apr 8, 2023 at 8:02
  • But apparently the solution you wrote have a problem, that you want to solve. What is the problem with your solution? Why do you want to rewrite it? Please edit your question to give us more details. Commented Apr 8, 2023 at 8:14
  • @Someprogrammerdude i want to improve my solution to optimize the time and space. So how does it be implemented which not use loop? Commented Apr 8, 2023 at 8:24

1 Answer 1

2

Here you go, converted to tail recursion by using an accumulator variable to store the intermediate results of the computation

long long x(int n, int i, long long acc) {
    if (i == n) return acc;
    return x(n, i + 1, acc + (n - i) * (n - i) * x(i));
}

long long x(int n) {
    return x(n, 0, 1);
}
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.