1

Is there a way to convert this recursive algorithm to iterative without using stacks?

public static float T1(int n, float y) {
    if (n == 0)
        return y;
    if (n == 1)
        return 1;

    return 2 * y * T1(n - 1, y) - T1(n - 2, y);
}

What keeps me confused is having two calls inside the recursion, and I'm not sure how to convert that using loops.

3
  • It looks like it should be perfectly possible with a single loop, keeping track of the result from the last two iterations to calculate the result for the current iteration. Commented May 15, 2016 at 14:54
  • Could you elaborate please? Commented May 15, 2016 at 14:59
  • OK, posting an answer Commented May 15, 2016 at 15:16

1 Answer 1

2

Here is a way to do the same calculation with a for loop.

public static float T1(int n, float y) {
    if (n==0) return y;
    if (n==1) return 1;
    float p1 = 1, p2 = y; // track the previous two values
    for (int i=2; i <= n; ++i) {
        float p = 2*y*p1 - p2; // calculate the result for this iteration
        p2 = p1; // update the previous values to be used in the next iteration
        p1 = p;
    }
    return p1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was trying to do something with a while loop but wasn't really successful. Thing that confused me the most is two recursive calls. Thanks for clearing this up!

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.