2

I always have problem trying to convert a recursive algorithm which i created that returns 2 recursive call until the base case is met.

It's easy to like track back what each recursive call do but converting them to iteration is a little confusing.

For example this recursive function

BEGIN SEQ(n)
   if (n == 1)
     return 3;
   
  else if (n == 2)
     return 2;

  else 
     return SEQ(n - 2) + SEQ(n - 1)

This is rather straight forward when i try to rubber duck my way through the recursive which produces the follow process

SEQ(6) = SEQ(4) + SEQ(5)

SEQ(5) = SEQ(3) + SEQ(4)

SEQ(4) = SEQ(2) + SEQ(3)

SEQ(3) = SEQ(1) + SEQ(2)

SEQ(2) = 2

SEQ(3) = 3 + 2 = 5

SEQ(4) = 2 + 5 = 7

SEQ(5) = 5 + 7 = 12

SEQ(6) = 7 + 12 = 19

However, i can't seems to figure out an iteration way that return exactly how the recursive does

3
  • The algorithm does not quite match the example. Did you mean return SEQ(n-2) + SEQ(n-1) in the last line? Commented Nov 10, 2016 at 5:31
  • Sorry, typo error. Commented Nov 10, 2016 at 5:32
  • Apart from the starting values this is built in the same way as the fibonacci sequence. Any iterative program you find for that is easy to modify. Commented Nov 10, 2016 at 5:36

1 Answer 1

4

Your iteration method in C# could look like this:

public static int SEQ(int n)
{
    if (n == 1)
    {
        return 3;
    }

    if (n == 2)
    {
        return 2;
    }
    var first = 3;
    var second = 2;

    for (var i = 3; i <= n; i++)
    {
        second += first;
        first = second - first;
    }


    return second;
}
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.