2

Lets assume I have a loop for Foo.

int Foo(int n)
{
   if (n <= 1)
      return 2;
   else
      return Foo(n-1) * Foo(n-2) * Foo (n-3);
}

How many call will occur If i Call Foo(3) and what would be the result...

Thanks

4
  • 2
    Why don't you run it and find out? Commented Jul 20, 2010 at 23:14
  • I need to be able to trade this by hand i am expecting something similar to this in the exam :D Commented Jul 20, 2010 at 23:18
  • 7 calls: ideone.com/0LU9T Commented Jul 20, 2010 at 23:30
  • How many calls occur? I am kind of confused... Commented Jul 20, 2010 at 23:33

4 Answers 4

6

Foo(3) calls Foo(2), Foo(1) and Foo(0)

Foo(1) and Foo(0) return immediately. Now apply the same logic for Foo(2), which doesn't return immediately.

To get the result, draw a tree like this:

            Foo(3)
      /       |        \
   Foo(2)   Foo(1)   Foo(0)

Continue drawing the tree until you have recursive calls that return immediately (for which the first if returns true), then use those results to calculate the values that are higher in the tree.

You can use the tree to figure out how many recursive calls are made too.

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

1 Comment

@bubdada: Then, to make sure you understand, try it with Foo(5). Make a note of how many times you end up invoking the function for any given input value (i.e. how many times do you end up calling Foo(0), Foo(1), Foo(2), Foo(3), Foo(4), and Foo(5)?). For extra credit, figure out a way to cut down on the duplication, given that Foo should be returning the same value given the same input.
2

Pass 1: Foo(3)

Pass 2: Foo(2) * Foo(1) * Foo(0)

Pass 3: Foo(1) * Foo(0) * Foo(-1) * 2 * 2

Result: 2 * 2 * 2 * 2 * 2 = 32

Comments

0

Foo(3) would get called 7 times.

Comments

0

How about:

int Foo(int n)
{
   cout << "Foo(" << n << ")" << endl;
   if (n <= 1)
      return 2;
   else
      return Foo(n-1) * Foo(n-2) * Foo (n-3);
}

2 Comments

I need to write more then 20 lines of code to be able to run on my system. Because we are using a crappy version of C++ but thanks thought...
@bubdada: You can't even use printf?

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.